[clang] [clang-format] Add SpaceAfterCompoundLiteralType option (PR #190075)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 3 12:36:58 PDT 2026
https://github.com/itsmomo16 updated https://github.com/llvm/llvm-project/pull/190075
>From 67af6f050f9ee8463920ecdb59a93b67038bcacb Mon Sep 17 00:00:00 2001
From: root <root at momolaptop.>
Date: Wed, 1 Apr 2026 18:12:42 -0400
Subject: [PATCH] [clang-format] Add SpaceAfterCompoundLiteralType option
Add a new SpaceAfterCompoundLiteralType option to control whether
a space is inserted between the type and opening brace in compound
literals, e.g. '(int) {1, 2, 3}' vs '(int){1, 2, 3}'.
This behavior was removed in #180179 with no option to restore it.
Fixes #189171.
---
clang/include/clang/Format/Format.h | 12872 +++---
clang/lib/Format/Format.cpp | 9541 ++---
clang/lib/Format/TokenAnnotator.cpp | 13375 +++---
clang/unittests/Format/FormatTest.cpp | 52444 ++++++++++++------------
4 files changed, 44172 insertions(+), 44060 deletions(-)
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 8c90cc2e98121..3c4dd25b59fb5 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1,6432 +1,6440 @@
-//===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-///
-/// \file
-/// Various functions to configurably format source code.
-///
-//===----------------------------------------------------------------------===//
-
-#ifndef LLVM_CLANG_FORMAT_FORMAT_H
-#define LLVM_CLANG_FORMAT_FORMAT_H
-
-#include "clang/Basic/LangOptions.h"
-#include "clang/Basic/TokenKinds.h"
-#include "clang/Tooling/Core/Replacement.h"
-#include "clang/Tooling/Inclusions/IncludeStyle.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/Support/Regex.h"
-#include "llvm/Support/SourceMgr.h"
-#include <optional>
-#include <system_error>
-
-namespace llvm {
-namespace vfs {
-class FileSystem;
-}
-} // namespace llvm
-
-namespace clang {
-namespace format {
-
-enum class ParseError {
- Success = 0,
- Error,
- Unsuitable,
- BinPackTrailingCommaConflict,
- InvalidQualifierSpecified,
- DuplicateQualifierSpecified,
- MissingQualifierType,
- MissingQualifierOrder
-};
-class ParseErrorCategory final : public std::error_category {
-public:
- const char *name() const noexcept override;
- std::string message(int EV) const override;
-};
-const std::error_category &getParseCategory();
-std::error_code make_error_code(ParseError e);
-
-/// The ``FormatStyle`` is used to configure the formatting to follow
-/// specific guidelines.
-struct FormatStyle {
- // If the BasedOn: was InheritParentConfig and this style needs the file from
- // the parent directories. It is not part of the actual style for formatting.
- // Thus the // instead of ///.
- std::string InheritConfig;
-
- /// The extra indent or outdent of access modifiers, e.g. ``public:``.
- /// \version 3.3
- int AccessModifierOffset;
-
- /// If ``true``, horizontally aligns arguments after an open bracket.
- ///
- /// \code
- /// true: vs. false
- /// someLongFunction(argument1, someLongFunction(argument1,
- /// argument2); argument2);
- /// \endcode
- ///
- /// \note
- /// As of clang-format 22 this option is a bool with the previous
- /// option of ``Align`` replaced with ``true``, ``DontAlign`` replaced
- /// with ``false``, and the options of ``AlwaysBreak`` and ``BlockIndent``
- /// replaced with ``true`` and with setting of new style options using
- /// ``BreakAfterOpenBracketBracedList``, ``BreakAfterOpenBracketFunction``,
- /// ``BreakAfterOpenBracketIf``, ``BreakBeforeCloseBracketBracedList``,
- /// ``BreakBeforeCloseBracketFunction``, and ``BreakBeforeCloseBracketIf``.
- /// \endnote
- ///
- /// This applies to round brackets (parentheses), angle brackets and square
- /// brackets.
- /// \version 3.8
- bool AlignAfterOpenBracket;
-
- /// Different style for aligning array initializers.
- enum ArrayInitializerAlignmentStyle : int8_t {
- /// Align array column and left justify the columns e.g.:
- /// \code
- /// struct test demo[] =
- /// {
- /// {56, 23, "hello"},
- /// {-1, 93463, "world"},
- /// {7, 5, "!!" }
- /// };
- /// \endcode
- AIAS_Left,
- /// Align array column and right justify the columns e.g.:
- /// \code
- /// struct test demo[] =
- /// {
- /// {56, 23, "hello"},
- /// {-1, 93463, "world"},
- /// { 7, 5, "!!"}
- /// };
- /// \endcode
- AIAS_Right,
- /// Don't align array initializer columns.
- AIAS_None
- };
- /// If not ``None``, when using initialization for an array of structs
- /// aligns the fields into columns.
- ///
- /// \note
- /// As of clang-format 15 this option only applied to arrays with equal
- /// number of columns per row.
- /// \endnote
- ///
- /// \version 13
- ArrayInitializerAlignmentStyle AlignArrayOfStructures;
-
- /// Alignment options.
- ///
- /// They can also be read as a whole for compatibility. The choices are:
- ///
- /// * ``None``
- /// * ``Consecutive``
- /// * ``AcrossEmptyLines``
- /// * ``AcrossComments``
- /// * ``AcrossEmptyLinesAndComments``
- ///
- /// For example, to align across empty lines and not across comments, either
- /// of these work.
- /// \code
- /// <option-name>: AcrossEmptyLines
- ///
- /// <option-name>:
- /// Enabled: true
- /// AcrossEmptyLines: true
- /// AcrossComments: false
- /// \endcode
- struct AlignConsecutiveStyle {
- /// Whether aligning is enabled.
- /// \code
- /// #define SHORT_NAME 42
- /// #define LONGER_NAME 0x007f
- /// #define EVEN_LONGER_NAME (2)
- /// #define foo(x) (x * x)
- /// #define bar(y, z) (y + z)
- ///
- /// int a = 1;
- /// int somelongname = 2;
- /// double c = 3;
- ///
- /// int aaaa : 1;
- /// int b : 12;
- /// int ccc : 8;
- ///
- /// int aaaa = 12;
- /// float b = 23;
- /// std::string ccc;
- /// \endcode
- bool Enabled;
- /// Whether to align across empty lines.
- /// \code
- /// true:
- /// int a = 1;
- /// int somelongname = 2;
- /// double c = 3;
- ///
- /// int d = 3;
- ///
- /// false:
- /// int a = 1;
- /// int somelongname = 2;
- /// double c = 3;
- ///
- /// int d = 3;
- /// \endcode
- bool AcrossEmptyLines;
- /// Whether to align across comments.
- /// \code
- /// true:
- /// int d = 3;
- /// /* A comment. */
- /// double e = 4;
- ///
- /// false:
- /// int d = 3;
- /// /* A comment. */
- /// double e = 4;
- /// \endcode
- bool AcrossComments;
- /// Only for ``AlignConsecutiveAssignments``. Whether compound assignments
- /// like ``+=`` are aligned along with ``=``.
- /// \code
- /// true:
- /// a &= 2;
- /// bbb = 2;
- ///
- /// false:
- /// a &= 2;
- /// bbb = 2;
- /// \endcode
- bool AlignCompound;
- /// Only for ``AlignConsecutiveDeclarations``. Whether function declarations
- /// are aligned.
- /// \code
- /// true:
- /// unsigned int f1(void);
- /// void f2(void);
- /// size_t f3(void);
- ///
- /// false:
- /// unsigned int f1(void);
- /// void f2(void);
- /// size_t f3(void);
- /// \endcode
- bool AlignFunctionDeclarations;
- /// Only for ``AlignConsecutiveDeclarations``. Whether function pointers are
- /// aligned.
- /// \code
- /// true:
- /// unsigned i;
- /// int &r;
- /// int *p;
- /// int (*f)();
- ///
- /// false:
- /// unsigned i;
- /// int &r;
- /// int *p;
- /// int (*f)();
- /// \endcode
- bool AlignFunctionPointers;
- /// Only for ``AlignConsecutiveAssignments``. Whether short assignment
- /// operators are left-padded to the same length as long ones in order to
- /// put all assignment operators to the right of the left hand side.
- /// \code
- /// true:
- /// a >>= 2;
- /// bbb = 2;
- ///
- /// a = 2;
- /// bbb >>= 2;
- ///
- /// false:
- /// a >>= 2;
- /// bbb = 2;
- ///
- /// a = 2;
- /// bbb >>= 2;
- /// \endcode
- bool PadOperators;
- bool operator==(const AlignConsecutiveStyle &R) const {
- return Enabled == R.Enabled && AcrossEmptyLines == R.AcrossEmptyLines &&
- AcrossComments == R.AcrossComments &&
- AlignCompound == R.AlignCompound &&
- AlignFunctionDeclarations == R.AlignFunctionDeclarations &&
- AlignFunctionPointers == R.AlignFunctionPointers &&
- PadOperators == R.PadOperators;
- }
- bool operator!=(const AlignConsecutiveStyle &R) const {
- return !(*this == R);
- }
- };
-
- /// Style of aligning consecutive macro definitions.
- ///
- /// ``Consecutive`` will result in formattings like:
- /// \code
- /// #define SHORT_NAME 42
- /// #define LONGER_NAME 0x007f
- /// #define EVEN_LONGER_NAME (2)
- /// #define foo(x) (x * x)
- /// #define bar(y, z) (y + z)
- /// \endcode
- /// \version 9
- AlignConsecutiveStyle AlignConsecutiveMacros;
- /// Style of aligning consecutive assignments.
- ///
- /// ``Consecutive`` will result in formattings like:
- /// \code
- /// int a = 1;
- /// int somelongname = 2;
- /// double c = 3;
- /// \endcode
- /// \version 3.8
- AlignConsecutiveStyle AlignConsecutiveAssignments;
- /// Style of aligning consecutive bit fields.
- ///
- /// ``Consecutive`` will align the bitfield separators of consecutive lines.
- /// This will result in formattings like:
- /// \code
- /// int aaaa : 1;
- /// int b : 12;
- /// int ccc : 8;
- /// \endcode
- /// \version 11
- AlignConsecutiveStyle AlignConsecutiveBitFields;
- /// Style of aligning consecutive declarations.
- ///
- /// ``Consecutive`` will align the declaration names of consecutive lines.
- /// This will result in formattings like:
- /// \code
- /// int aaaa = 12;
- /// float b = 23;
- /// std::string ccc;
- /// \endcode
- /// \version 3.8
- AlignConsecutiveStyle AlignConsecutiveDeclarations;
-
- /// Alignment options.
- ///
- struct ShortCaseStatementsAlignmentStyle {
- /// Whether aligning is enabled.
- /// \code
- /// true:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- /// default: return "";
- /// }
- ///
- /// false:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- /// default: return "";
- /// }
- /// \endcode
- bool Enabled;
- /// Whether to align across empty lines.
- /// \code
- /// true:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- ///
- /// default: return "";
- /// }
- ///
- /// false:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- ///
- /// default: return "";
- /// }
- /// \endcode
- bool AcrossEmptyLines;
- /// Whether to align across comments.
- /// \code
- /// true:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- /// /* A comment. */
- /// default: return "";
- /// }
- ///
- /// false:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- /// /* A comment. */
- /// default: return "";
- /// }
- /// \endcode
- bool AcrossComments;
- /// Whether to align the case arrows when aligning short case expressions.
- /// \code{.java}
- /// true:
- /// i = switch (day) {
- /// case THURSDAY, SATURDAY -> 8;
- /// case WEDNESDAY -> 9;
- /// default -> 0;
- /// };
- ///
- /// false:
- /// i = switch (day) {
- /// case THURSDAY, SATURDAY -> 8;
- /// case WEDNESDAY -> 9;
- /// default -> 0;
- /// };
- /// \endcode
- bool AlignCaseArrows;
- /// Whether aligned case labels are aligned on the colon, or on the tokens
- /// after the colon.
- /// \code
- /// true:
- /// switch (level) {
- /// case log::info : return "info:";
- /// case log::warning: return "warning:";
- /// default : return "";
- /// }
- ///
- /// false:
- /// switch (level) {
- /// case log::info: return "info:";
- /// case log::warning: return "warning:";
- /// default: return "";
- /// }
- /// \endcode
- bool AlignCaseColons;
- bool operator==(const ShortCaseStatementsAlignmentStyle &R) const {
- return Enabled == R.Enabled && AcrossEmptyLines == R.AcrossEmptyLines &&
- AcrossComments == R.AcrossComments &&
- AlignCaseArrows == R.AlignCaseArrows &&
- AlignCaseColons == R.AlignCaseColons;
- }
- };
-
- /// Style of aligning consecutive short case labels.
- /// Only applies if ``AllowShortCaseExpressionOnASingleLine`` or
- /// ``AllowShortCaseLabelsOnASingleLine`` is ``true``.
- ///
- /// \code{.yaml}
- /// # Example of usage:
- /// AlignConsecutiveShortCaseStatements:
- /// Enabled: true
- /// AcrossEmptyLines: true
- /// AcrossComments: true
- /// AlignCaseColons: false
- /// \endcode
- /// \version 17
- ShortCaseStatementsAlignmentStyle AlignConsecutiveShortCaseStatements;
-
- /// Style of aligning consecutive TableGen DAGArg operator colons.
- /// If enabled, align the colon inside DAGArg which have line break inside.
- /// This works only when TableGenBreakInsideDAGArg is BreakElements or
- /// BreakAll and the DAGArg is not excepted by
- /// TableGenBreakingDAGArgOperators's effect.
- /// \code
- /// let dagarg = (ins
- /// a :$src1,
- /// aa :$src2,
- /// aaa:$src3
- /// )
- /// \endcode
- /// \version 19
- AlignConsecutiveStyle AlignConsecutiveTableGenBreakingDAGArgColons;
-
- /// Style of aligning consecutive TableGen cond operator colons.
- /// Align the colons of cases inside !cond operators.
- /// \code
- /// !cond(!eq(size, 1) : 1,
- /// !eq(size, 16): 1,
- /// true : 0)
- /// \endcode
- /// \version 19
- AlignConsecutiveStyle AlignConsecutiveTableGenCondOperatorColons;
-
- /// Style of aligning consecutive TableGen definition colons.
- /// This aligns the inheritance colons of consecutive definitions.
- /// \code
- /// def Def : Parent {}
- /// def DefDef : Parent {}
- /// def DefDefDef : Parent {}
- /// \endcode
- /// \version 19
- AlignConsecutiveStyle AlignConsecutiveTableGenDefinitionColons;
-
- /// Different styles for aligning escaped newlines.
- enum EscapedNewlineAlignmentStyle : int8_t {
- /// Don't align escaped newlines.
- /// \code
- /// #define A \
- /// int aaaa; \
- /// int b; \
- /// int dddddddddd;
- /// \endcode
- ENAS_DontAlign,
- /// Align escaped newlines as far left as possible.
- /// \code
- /// #define A \
- /// int aaaa; \
- /// int b; \
- /// int dddddddddd;
- /// \endcode
- ENAS_Left,
- /// Align escaped newlines as far left as possible, using the last line of
- /// the preprocessor directive as the reference if it's the longest.
- /// \code
- /// #define A \
- /// int aaaa; \
- /// int b; \
- /// int dddddddddd;
- /// \endcode
- ENAS_LeftWithLastLine,
- /// Align escaped newlines in the right-most column.
- /// \code
- /// #define A \
- /// int aaaa; \
- /// int b; \
- /// int dddddddddd;
- /// \endcode
- ENAS_Right,
- };
-
- /// Options for aligning backslashes in escaped newlines.
- /// \version 5
- EscapedNewlineAlignmentStyle AlignEscapedNewlines;
-
- /// Different styles for aligning operands.
- enum OperandAlignmentStyle : int8_t {
- /// Do not align operands of binary and ternary expressions.
- /// The wrapped lines are indented ``ContinuationIndentWidth`` spaces from
- /// the start of the line.
- OAS_DontAlign,
- /// Horizontally align operands of binary and ternary expressions.
- ///
- /// Specifically, this aligns operands of a single expression that needs
- /// to be split over multiple lines, e.g.:
- /// \code
- /// int aaa = bbbbbbbbbbbbbbb +
- /// ccccccccccccccc;
- /// \endcode
- ///
- /// When ``BreakBeforeBinaryOperators`` is set, the wrapped operator is
- /// aligned with the operand on the first line.
- /// \code
- /// int aaa = bbbbbbbbbbbbbbb
- /// + ccccccccccccccc;
- /// \endcode
- OAS_Align,
- /// Horizontally align operands of binary and ternary expressions.
- ///
- /// This is similar to ``OAS_Align``, except when
- /// ``BreakBeforeBinaryOperators`` is set, the operator is un-indented so
- /// that the wrapped operand is aligned with the operand on the first line.
- /// \code
- /// int aaa = bbbbbbbbbbbbbbb
- /// + ccccccccccccccc;
- /// \endcode
- OAS_AlignAfterOperator,
- };
-
- /// If ``true``, horizontally align operands of binary and ternary
- /// expressions.
- /// \version 3.5
- OperandAlignmentStyle AlignOperands;
-
- /// Enums for AlignTrailingComments
- enum TrailingCommentsAlignmentKinds : int8_t {
- /// Leave trailing comments as they are.
- /// \code
- /// int a; // comment
- /// int ab; // comment
- ///
- /// int abc; // comment
- /// int abcd; // comment
- /// \endcode
- TCAS_Leave,
- /// Align trailing comments.
- /// \code
- /// int a; // comment
- /// int ab; // comment
- ///
- /// int abc; // comment
- /// int abcd; // comment
- /// \endcode
- TCAS_Always,
- /// Don't align trailing comments but other formatter applies.
- /// \code
- /// int a; // comment
- /// int ab; // comment
- ///
- /// int abc; // comment
- /// int abcd; // comment
- /// \endcode
- TCAS_Never,
- };
-
- /// Alignment options
- struct TrailingCommentsAlignmentStyle {
- /// Specifies the way to align trailing comments.
- TrailingCommentsAlignmentKinds Kind;
- /// How many empty lines to apply alignment.
- /// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
- /// it formats like below.
- /// \code
- /// int a; // all these
- ///
- /// int ab; // comments are
- ///
- ///
- /// int abcdef; // aligned
- /// \endcode
- ///
- /// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
- /// to 1, it formats like below.
- /// \code
- /// int a; // these are
- ///
- /// int ab; // aligned
- ///
- ///
- /// int abcdef; // but this isn't
- /// \endcode
- unsigned OverEmptyLines;
- /// If comments following preprocessor directive should be aligned with
- /// comments that don't.
- /// \code
- /// true: false:
- /// #define A // Comment vs. #define A // Comment
- /// #define AB // Aligned #define AB // Aligned
- /// int i; // Aligned int i; // Not aligned
- /// \endcode
- bool AlignPPAndNotPP;
-
- bool operator==(const TrailingCommentsAlignmentStyle &R) const {
- return Kind == R.Kind && OverEmptyLines == R.OverEmptyLines &&
- AlignPPAndNotPP == R.AlignPPAndNotPP;
- }
- bool operator!=(const TrailingCommentsAlignmentStyle &R) const {
- return !(*this == R);
- }
- };
-
- /// Control of trailing comments.
- ///
- /// The alignment stops at closing braces after a line break, and only
- /// followed by other closing braces, a (``do-``) ``while``, a lambda call, or
- /// a semicolon.
- ///
- /// \note
- /// As of clang-format 16 this option is not a bool but can be set
- /// to the options. Conventional bool options still can be parsed as before.
- /// \endnote
- ///
- /// \code{.yaml}
- /// # Example of usage:
- /// AlignTrailingComments:
- /// Kind: Always
- /// OverEmptyLines: 2
- /// \endcode
- /// \version 3.7
- TrailingCommentsAlignmentStyle AlignTrailingComments;
-
- /// If a function call or braced initializer list doesn't fit on a line, allow
- /// putting all arguments onto the next line, even if ``BinPackArguments`` is
- /// ``false``.
- /// \code
- /// true:
- /// callFunction(
- /// a, b, c, d);
- ///
- /// false:
- /// callFunction(a,
- /// b,
- /// c,
- /// d);
- /// \endcode
- /// \version 9
- bool AllowAllArgumentsOnNextLine;
-
- /// This option is **deprecated**. See ``NextLine`` of
- /// ``PackConstructorInitializers``.
- /// \version 9
- // bool AllowAllConstructorInitializersOnNextLine;
-
- /// If the function declaration doesn't fit on a line,
- /// allow putting all parameters of a function declaration onto
- /// the next line even if ``BinPackParameters`` is ``OnePerLine``.
- /// \code
- /// true:
- /// void myFunction(
- /// int a, int b, int c, int d, int e);
- ///
- /// false:
- /// void myFunction(int a,
- /// int b,
- /// int c,
- /// int d,
- /// int e);
- /// \endcode
- /// \version 3.3
- bool AllowAllParametersOfDeclarationOnNextLine;
-
- /// Different ways to break before a noexcept specifier.
- enum BreakBeforeNoexceptSpecifierStyle : int8_t {
- /// No line break allowed.
- /// \code
- /// void foo(int arg1,
- /// double arg2) noexcept;
- ///
- /// void bar(int arg1, double arg2) noexcept(
- /// noexcept(baz(arg1)) &&
- /// noexcept(baz(arg2)));
- /// \endcode
- BBNSS_Never,
- /// For a simple ``noexcept`` there is no line break allowed, but when we
- /// have a condition it is.
- /// \code
- /// void foo(int arg1,
- /// double arg2) noexcept;
- ///
- /// void bar(int arg1, double arg2)
- /// noexcept(noexcept(baz(arg1)) &&
- /// noexcept(baz(arg2)));
- /// \endcode
- BBNSS_OnlyWithParen,
- /// Line breaks are allowed. But note that because of the associated
- /// penalties ``clang-format`` often prefers not to break before the
- /// ``noexcept``.
- /// \code
- /// void foo(int arg1,
- /// double arg2) noexcept;
- ///
- /// void bar(int arg1, double arg2)
- /// noexcept(noexcept(baz(arg1)) &&
- /// noexcept(baz(arg2)));
- /// \endcode
- BBNSS_Always,
- };
-
- /// Controls if there could be a line break before a ``noexcept`` specifier.
- /// \version 18
- BreakBeforeNoexceptSpecifierStyle AllowBreakBeforeNoexceptSpecifier;
-
- /// Allow breaking before ``Q_Property`` keywords ``READ``, ``WRITE``, etc. as
- /// if they were preceded by a comma (``,``). This allows them to be formatted
- /// according to ``BinPackParameters``.
- /// \version 22
- bool AllowBreakBeforeQtProperty;
-
- /// Different styles for merging short blocks containing at most one
- /// statement.
- enum ShortBlockStyle : int8_t {
- /// Never merge blocks into a single line.
- /// \code
- /// while (true) {
- /// }
- /// while (true) {
- /// continue;
- /// }
- /// \endcode
- SBS_Never,
- /// Only merge empty blocks.
- /// \code
- /// while (true) {}
- /// while (true) {
- /// continue;
- /// }
- /// \endcode
- SBS_Empty,
- /// Always merge short blocks into a single line.
- /// \code
- /// while (true) {}
- /// while (true) { continue; }
- /// \endcode
- SBS_Always,
- };
-
- /// Dependent on the value, ``while (true) { continue; }`` can be put on a
- /// single line.
- /// \version 3.5
- ShortBlockStyle AllowShortBlocksOnASingleLine;
-
- /// Whether to merge a short switch labeled rule into a single line.
- /// \code{.java}
- /// true: false:
- /// switch (a) { vs. switch (a) {
- /// case 1 -> 1; case 1 ->
- /// default -> 0; 1;
- /// }; default ->
- /// 0;
- /// };
- /// \endcode
- /// \version 19
- bool AllowShortCaseExpressionOnASingleLine;
-
- /// If ``true``, short case labels will be contracted to a single line.
- /// \code
- /// true: false:
- /// switch (a) { vs. switch (a) {
- /// case 1: x = 1; break; case 1:
- /// case 2: return; x = 1;
- /// } break;
- /// case 2:
- /// return;
- /// }
- /// \endcode
- /// \version 3.6
- bool AllowShortCaseLabelsOnASingleLine;
-
- /// Allow short compound requirement on a single line.
- /// \code
- /// true:
- /// template <typename T>
- /// concept c = requires(T x) {
- /// { x + 1 } -> std::same_as<int>;
- /// };
- ///
- /// false:
- /// template <typename T>
- /// concept c = requires(T x) {
- /// {
- /// x + 1
- /// } -> std::same_as<int>;
- /// };
- /// \endcode
- /// \version 18
- bool AllowShortCompoundRequirementOnASingleLine;
-
- /// Allow short enums on a single line.
- /// \code
- /// true:
- /// enum { A, B } myEnum;
- ///
- /// false:
- /// enum {
- /// A,
- /// B
- /// } myEnum;
- /// \endcode
- /// \version 11
- bool AllowShortEnumsOnASingleLine;
-
- /// Different styles for merging short functions containing at most one
- /// statement.
- ///
- /// They can be read as a whole for compatibility. The choices are:
- ///
- /// * ``None``
- /// Never merge functions into a single line.
- ///
- /// * ``InlineOnly``
- /// Only merge functions defined inside a class. Same as ``inline``,
- /// except it does not implies ``empty``: i.e. top level empty functions
- /// are not merged either. This option is **deprecated** and is retained
- /// for backwards compatibility. See ``Inline`` of ``ShortFunctionStyle``.
- /// \code
- /// class Foo {
- /// void f() { foo(); }
- /// };
- /// void f() {
- /// foo();
- /// }
- /// void f() {
- /// }
- /// \endcode
- ///
- /// * ``Empty``
- /// Only merge empty functions. This option is **deprecated** and is
- /// retained for backwards compatibility. See ``Empty`` of
- /// ``ShortFunctionStyle``.
- /// \code
- /// void f() {}
- /// void f2() {
- /// bar2();
- /// }
- /// \endcode
- ///
- /// * ``Inline``
- /// Only merge functions defined inside a class. Implies ``empty``. This
- /// option is **deprecated** and is retained for backwards compatibility.
- /// See ``Inline`` and ``Empty`` of ``ShortFunctionStyle``.
- /// \code
- /// class Foo {
- /// void f() { foo(); }
- /// };
- /// void f() {
- /// foo();
- /// }
- /// void f() {}
- /// \endcode
- ///
- /// * ``All``
- /// Merge all functions fitting on a single line.
- /// \code
- /// class Foo {
- /// void f() { foo(); }
- /// };
- /// void f() { bar(); }
- /// \endcode
- ///
- /// Also can be specified as a nested configuration flag:
- /// \code
- /// # Example of usage:
- /// AllowShortFunctionsOnASingleLine: InlineOnly
- ///
- /// # or more granular control:
- /// AllowShortFunctionsOnASingleLine:
- /// Empty: false
- /// Inline: true
- /// Other: false
- /// \endcode
- struct ShortFunctionStyle {
- /// Merge top-level empty functions.
- /// \code
- /// void f() {}
- /// void f2() {
- /// bar2();
- /// }
- /// void f3() { /* comment */ }
- /// \endcode
- bool Empty;
- /// Merge functions defined inside a class.
- /// \code
- /// class Foo {
- /// void f() { foo(); }
- /// void g() {}
- /// };
- /// void f() {
- /// foo();
- /// }
- /// void f() {
- /// }
- /// \endcode
- bool Inline;
- /// Merge all functions fitting on a single line. Please note that this
- /// control does not include Empty
- /// \code
- /// class Foo {
- /// void f() { foo(); }
- /// };
- /// void f() { bar(); }
- /// \endcode
- bool Other;
-
- bool operator==(const ShortFunctionStyle &R) const {
- return Empty == R.Empty && Inline == R.Inline && Other == R.Other;
- }
- bool operator!=(const ShortFunctionStyle &R) const { return !(*this == R); }
- ShortFunctionStyle() : Empty(false), Inline(false), Other(false) {}
- ShortFunctionStyle(bool Empty, bool Inline, bool Other)
- : Empty(Empty), Inline(Inline), Other(Other) {}
- bool isAll() const { return Empty && Inline && Other; }
- static ShortFunctionStyle setEmptyOnly() {
- return ShortFunctionStyle(true, false, false);
- }
- static ShortFunctionStyle setEmptyAndInline() {
- return ShortFunctionStyle(true, true, false);
- }
- static ShortFunctionStyle setInlineOnly() {
- return ShortFunctionStyle(false, true, false);
- }
- static ShortFunctionStyle setAll() {
- return ShortFunctionStyle(true, true, true);
- }
- };
-
- /// Dependent on the value, ``int f() { return 0; }`` can be put on a
- /// single line.
- /// \version 3.5
- ShortFunctionStyle AllowShortFunctionsOnASingleLine;
-
- /// Different styles for handling short if statements.
- enum ShortIfStyle : int8_t {
- /// Never put short ifs on the same line.
- /// \code
- /// if (a)
- /// return;
- ///
- /// if (b)
- /// return;
- /// else
- /// return;
- ///
- /// if (c)
- /// return;
- /// else {
- /// return;
- /// }
- /// \endcode
- SIS_Never,
- /// Put short ifs on the same line only if there is no else statement.
- /// \code
- /// if (a) return;
- ///
- /// if (b)
- /// return;
- /// else
- /// return;
- ///
- /// if (c)
- /// return;
- /// else {
- /// return;
- /// }
- /// \endcode
- SIS_WithoutElse,
- /// Put short ifs, but not else ifs nor else statements, on the same line.
- /// \code
- /// if (a) return;
- ///
- /// if (b) return;
- /// else if (b)
- /// return;
- /// else
- /// return;
- ///
- /// if (c) return;
- /// else {
- /// return;
- /// }
- /// \endcode
- SIS_OnlyFirstIf,
- /// Always put short ifs, else ifs and else statements on the same
- /// line.
- /// \code
- /// if (a) return;
- ///
- /// if (b) return;
- /// else return;
- ///
- /// if (c) return;
- /// else {
- /// return;
- /// }
- /// \endcode
- SIS_AllIfsAndElse,
- };
-
- /// Dependent on the value, ``if (a) return;`` can be put on a single line.
- /// \version 3.3
- ShortIfStyle AllowShortIfStatementsOnASingleLine;
-
- /// Different styles for merging short lambdas containing at most one
- /// statement.
- enum ShortLambdaStyle : int8_t {
- /// Never merge lambdas into a single line.
- SLS_None,
- /// Only merge empty lambdas.
- /// \code
- /// auto lambda = [](int a) {};
- /// auto lambda2 = [](int a) {
- /// return a;
- /// };
- /// \endcode
- SLS_Empty,
- /// Merge lambda into a single line if the lambda is argument of a function.
- /// \code
- /// auto lambda = [](int x, int y) {
- /// return x < y;
- /// };
- /// sort(a.begin(), a.end(), [](int x, int y) { return x < y; });
- /// \endcode
- SLS_Inline,
- /// Merge all lambdas fitting on a single line.
- /// \code
- /// auto lambda = [](int a) {};
- /// auto lambda2 = [](int a) { return a; };
- /// \endcode
- SLS_All,
- };
-
- /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
- /// single line.
- /// \version 9
- ShortLambdaStyle AllowShortLambdasOnASingleLine;
-
- /// If ``true``, ``while (true) continue;`` can be put on a single
- /// line.
- /// \version 3.7
- bool AllowShortLoopsOnASingleLine;
-
- /// If ``true``, ``namespace a { class b; }`` can be put on a single line.
- /// \version 20
- bool AllowShortNamespacesOnASingleLine;
-
- /// Different styles for merging short records (``class``,``struct``, and
- /// ``union``).
- enum ShortRecordStyle : int8_t {
- /// Never merge records into a single line.
- SRS_Never,
- /// Only merge empty records if the opening brace was not wrapped,
- /// i.e. the corresponding ``BraceWrapping.After...`` option was not set.
- SRS_EmptyAndAttached,
- /// Only merge empty records.
- /// \code
- /// struct foo {};
- /// struct bar
- /// {
- /// int i;
- /// };
- /// \endcode
- SRS_Empty,
- /// Merge all records that fit on a single line.
- /// \code
- /// struct foo {};
- /// struct bar { int i; };
- /// \endcode
- SRS_Always
- };
-
- /// Dependent on the value, ``struct bar { int i; };`` can be put on a single
- /// line.
- /// \version 23
- ShortRecordStyle AllowShortRecordOnASingleLine;
-
- /// Different ways to break after the function definition return type.
- /// This option is **deprecated** and is retained for backwards compatibility.
- enum DefinitionReturnTypeBreakingStyle : int8_t {
- /// Break after return type automatically.
- /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
- DRTBS_None,
- /// Always break after the return type.
- DRTBS_All,
- /// Always break after the return types of top-level functions.
- DRTBS_TopLevel,
- };
-
- /// Different ways to break after the function definition or
- /// declaration return type.
- enum ReturnTypeBreakingStyle : int8_t {
- /// This is **deprecated**. See ``Automatic`` below.
- RTBS_None,
- /// Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
- /// \code
- /// class A {
- /// int f() { return 0; };
- /// };
- /// int f();
- /// int f() { return 1; }
- /// int
- /// LongName::AnotherLongName();
- /// \endcode
- RTBS_Automatic,
- /// Same as ``Automatic`` above, except that there is no break after short
- /// return types.
- /// \code
- /// class A {
- /// int f() { return 0; };
- /// };
- /// int f();
- /// int f() { return 1; }
- /// int LongName::
- /// AnotherLongName();
- /// \endcode
- RTBS_ExceptShortType,
- /// Always break after the return type.
- /// \code
- /// class A {
- /// int
- /// f() {
- /// return 0;
- /// };
- /// };
- /// int
- /// f();
- /// int
- /// f() {
- /// return 1;
- /// }
- /// int
- /// LongName::AnotherLongName();
- /// \endcode
- RTBS_All,
- /// Always break after the return types of top-level functions.
- /// \code
- /// class A {
- /// int f() { return 0; };
- /// };
- /// int
- /// f();
- /// int
- /// f() {
- /// return 1;
- /// }
- /// int
- /// LongName::AnotherLongName();
- /// \endcode
- RTBS_TopLevel,
- /// Always break after the return type of function definitions.
- /// \code
- /// class A {
- /// int
- /// f() {
- /// return 0;
- /// };
- /// };
- /// int f();
- /// int
- /// f() {
- /// return 1;
- /// }
- /// int
- /// LongName::AnotherLongName();
- /// \endcode
- RTBS_AllDefinitions,
- /// Always break after the return type of top-level definitions.
- /// \code
- /// class A {
- /// int f() { return 0; };
- /// };
- /// int f();
- /// int
- /// f() {
- /// return 1;
- /// }
- /// int
- /// LongName::AnotherLongName();
- /// \endcode
- RTBS_TopLevelDefinitions,
- };
-
- /// The function definition return type breaking style to use. This
- /// option is **deprecated** and is retained for backwards compatibility.
- /// \version 3.7
- DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
-
- /// This option is renamed to ``BreakAfterReturnType``.
- /// \version 3.8
- /// @deprecated
- // ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
-
- /// If ``true``, always break before multiline string literals.
- ///
- /// This flag is mean to make cases where there are multiple multiline strings
- /// in a file look more consistent. Thus, it will only take effect if wrapping
- /// the string at that point leads to it being indented
- /// ``ContinuationIndentWidth`` spaces from the start of the line.
- /// \code
- /// true: false:
- /// aaaa = vs. aaaa = "bbbb"
- /// "bbbb" "cccc";
- /// "cccc";
- /// \endcode
- /// \version 3.4
- bool AlwaysBreakBeforeMultilineStrings;
-
- /// Different ways to break after the template declaration.
- enum BreakTemplateDeclarationsStyle : int8_t {
- /// Do not change the line breaking before the declaration.
- /// \code
- /// template <typename T>
- /// T foo() {
- /// }
- /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
- /// int bbbbbbbbbbbbbbbbbbbbb) {
- /// }
- /// \endcode
- BTDS_Leave,
- /// Do not force break before declaration.
- /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
- /// \code
- /// template <typename T> T foo() {
- /// }
- /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
- /// int bbbbbbbbbbbbbbbbbbbbb) {
- /// }
- /// \endcode
- BTDS_No,
- /// Force break after template declaration only when the following
- /// declaration spans multiple lines.
- /// \code
- /// template <typename T> T foo() {
- /// }
- /// template <typename T>
- /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
- /// int bbbbbbbbbbbbbbbbbbbbb) {
- /// }
- /// \endcode
- BTDS_MultiLine,
- /// Always break after template declaration.
- /// \code
- /// template <typename T>
- /// T foo() {
- /// }
- /// template <typename T>
- /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
- /// int bbbbbbbbbbbbbbbbbbbbb) {
- /// }
- /// \endcode
- BTDS_Yes
- };
-
- /// This option is renamed to ``BreakTemplateDeclarations``.
- /// \version 3.4
- /// @deprecated
- // BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
-
- /// A vector of strings that should be interpreted as attributes/qualifiers
- /// instead of identifiers. This can be useful for language extensions or
- /// static analyzer annotations.
- ///
- /// For example:
- /// \code
- /// x = (char *__capability)&y;
- /// int function(void) __unused;
- /// void only_writes_to_buffer(char *__output buffer);
- /// \endcode
- ///
- /// In the .clang-format configuration file, this can be configured like:
- /// \code{.yaml}
- /// AttributeMacros: [__capability, __output, __unused]
- /// \endcode
- ///
- /// \version 12
- std::vector<std::string> AttributeMacros;
-
- /// If ``false``, a function call's arguments will either be all on the
- /// same line or will have one line each.
- /// \code
- /// true:
- /// void f() {
- /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
- /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
- /// }
- ///
- /// false:
- /// void f() {
- /// f(aaaaaaaaaaaaaaaaaaaa,
- /// aaaaaaaaaaaaaaaaaaaa,
- /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
- /// }
- /// \endcode
- /// \version 3.7
- bool BinPackArguments;
-
- /// If ``BinPackLongBracedList`` is ``true`` it overrides
- /// ``BinPackArguments`` if there are 20 or more items in a braced
- /// initializer list.
- /// \code
- /// BinPackLongBracedList: false vs. BinPackLongBracedList: true
- /// vector<int> x{ vector<int> x{1, 2, ...,
- /// 20, 21};
- /// 1,
- /// 2,
- /// ...,
- /// 20,
- /// 21};
- /// \endcode
- /// \version 21
- bool BinPackLongBracedList;
-
- /// Different way to try to fit all parameters on a line.
- enum BinPackParametersStyle : int8_t {
- /// Bin-pack parameters.
- /// \code
- /// void f(int a, int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
- /// int ccccccccccccccccccccccccccccccccccccccccccc);
- /// \endcode
- BPPS_BinPack,
- /// Put all parameters on the current line if they fit.
- /// Otherwise, put each one on its own line.
- /// \code
- /// void f(int a, int b, int c);
- ///
- /// void f(int a,
- /// int b,
- /// int ccccccccccccccccccccccccccccccccccccc);
- /// \endcode
- BPPS_OnePerLine,
- /// Always put each parameter on its own line.
- /// \code
- /// void f(int a,
- /// int b,
- /// int c);
- /// \endcode
- BPPS_AlwaysOnePerLine,
- };
-
- /// The bin pack parameters style to use.
- /// \version 3.7
- BinPackParametersStyle BinPackParameters;
-
- /// Styles for adding spacing around ``:`` in bitfield definitions.
- enum BitFieldColonSpacingStyle : int8_t {
- /// Add one space on each side of the ``:``
- /// \code
- /// unsigned bf : 2;
- /// \endcode
- BFCS_Both,
- /// Add no space around the ``:`` (except when needed for
- /// ``AlignConsecutiveBitFields``).
- /// \code
- /// unsigned bf:2;
- /// \endcode
- BFCS_None,
- /// Add space before the ``:`` only
- /// \code
- /// unsigned bf :2;
- /// \endcode
- BFCS_Before,
- /// Add space after the ``:`` only (space may be added before if
- /// needed for ``AlignConsecutiveBitFields``).
- /// \code
- /// unsigned bf: 2;
- /// \endcode
- BFCS_After
- };
- /// The BitFieldColonSpacingStyle to use for bitfields.
- /// \version 12
- BitFieldColonSpacingStyle BitFieldColonSpacing;
-
- /// The number of columns to use to indent the contents of braced init lists.
- /// If unset or negative, ``ContinuationIndentWidth`` is used.
- /// \code
- /// AlignAfterOpenBracket: AlwaysBreak
- /// BracedInitializerIndentWidth: 2
- ///
- /// void f() {
- /// SomeClass c{
- /// "foo",
- /// "bar",
- /// "baz",
- /// };
- /// auto s = SomeStruct{
- /// .foo = "foo",
- /// .bar = "bar",
- /// .baz = "baz",
- /// };
- /// SomeArrayT a[3] = {
- /// {
- /// foo,
- /// bar,
- /// },
- /// {
- /// foo,
- /// bar,
- /// },
- /// SomeArrayT{},
- /// };
- /// }
- /// \endcode
- /// \version 17
- int BracedInitializerIndentWidth;
-
- /// Different ways to wrap braces after control statements.
- enum BraceWrappingAfterControlStatementStyle : int8_t {
- /// Never wrap braces after a control statement.
- /// \code
- /// if (foo()) {
- /// } else {
- /// }
- /// for (int i = 0; i < 10; ++i) {
- /// }
- /// \endcode
- BWACS_Never,
- /// Only wrap braces after a multi-line control statement.
- /// \code
- /// if (foo && bar &&
- /// baz)
- /// {
- /// quux();
- /// }
- /// while (foo || bar) {
- /// }
- /// \endcode
- BWACS_MultiLine,
- /// Always wrap braces after a control statement.
- /// \code
- /// if (foo())
- /// {
- /// } else
- /// {}
- /// for (int i = 0; i < 10; ++i)
- /// {}
- /// \endcode
- BWACS_Always
- };
-
- /// Precise control over the wrapping of braces.
- /// \code
- /// # Should be declared this way:
- /// BreakBeforeBraces: Custom
- /// BraceWrapping:
- /// AfterClass: true
- /// \endcode
- struct BraceWrappingFlags {
- /// Wrap case labels.
- /// \code
- /// false: true:
- /// switch (foo) { vs. switch (foo) {
- /// case 1: { case 1:
- /// bar(); {
- /// break; bar();
- /// } break;
- /// default: { }
- /// plop(); default:
- /// } {
- /// } plop();
- /// }
- /// }
- /// \endcode
- bool AfterCaseLabel;
- /// Wrap class definitions.
- /// \code
- /// true:
- /// class foo
- /// {};
- ///
- /// false:
- /// class foo {};
- /// \endcode
- bool AfterClass;
-
- /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
- BraceWrappingAfterControlStatementStyle AfterControlStatement;
- /// Wrap enum definitions.
- /// \code
- /// true:
- /// enum X : int
- /// {
- /// B
- /// };
- ///
- /// false:
- /// enum X : int { B };
- /// \endcode
- bool AfterEnum;
- /// Wrap function definitions.
- /// \code
- /// true:
- /// void foo()
- /// {
- /// bar();
- /// bar2();
- /// }
- ///
- /// false:
- /// void foo() {
- /// bar();
- /// bar2();
- /// }
- /// \endcode
- bool AfterFunction;
- /// Wrap namespace definitions.
- /// \code
- /// true:
- /// namespace
- /// {
- /// int foo();
- /// int bar();
- /// }
- ///
- /// false:
- /// namespace {
- /// int foo();
- /// int bar();
- /// }
- /// \endcode
- bool AfterNamespace;
- /// Wrap ObjC definitions (interfaces, implementations...).
- /// \note
- /// @autoreleasepool and @synchronized blocks are wrapped
- /// according to ``AfterControlStatement`` flag.
- /// \endnote
- bool AfterObjCDeclaration;
- /// Wrap struct definitions.
- /// \code
- /// true:
- /// struct foo
- /// {
- /// int x;
- /// };
- ///
- /// false:
- /// struct foo {
- /// int x;
- /// };
- /// \endcode
- bool AfterStruct;
- /// Wrap union definitions.
- /// \code
- /// true:
- /// union foo
- /// {
- /// int x;
- /// }
- ///
- /// false:
- /// union foo {
- /// int x;
- /// }
- /// \endcode
- bool AfterUnion;
- /// Wrap extern blocks.
- /// \code
- /// true:
- /// extern "C"
- /// {
- /// int foo();
- /// }
- ///
- /// false:
- /// extern "C" {
- /// int foo();
- /// }
- /// \endcode
- bool AfterExternBlock; // Partially superseded by IndentExternBlock
- /// Wrap before ``catch``.
- /// \code
- /// true:
- /// try {
- /// foo();
- /// }
- /// catch () {
- /// }
- ///
- /// false:
- /// try {
- /// foo();
- /// } catch () {
- /// }
- /// \endcode
- bool BeforeCatch;
- /// Wrap before ``else``.
- /// \code
- /// true:
- /// if (foo()) {
- /// }
- /// else {
- /// }
- ///
- /// false:
- /// if (foo()) {
- /// } else {
- /// }
- /// \endcode
- bool BeforeElse;
- /// Wrap lambda block.
- /// \code
- /// true:
- /// connect(
- /// []()
- /// {
- /// foo();
- /// bar();
- /// });
- ///
- /// false:
- /// connect([]() {
- /// foo();
- /// bar();
- /// });
- /// \endcode
- bool BeforeLambdaBody;
- /// Wrap before ``while``.
- /// \code
- /// true:
- /// do {
- /// foo();
- /// }
- /// while (1);
- ///
- /// false:
- /// do {
- /// foo();
- /// } while (1);
- /// \endcode
- bool BeforeWhile;
- /// Indent the wrapped braces themselves.
- bool IndentBraces;
- /// If ``false``, empty function body can be put on a single line.
- /// This option is used only if the opening brace of the function has
- /// already been wrapped, i.e. the ``AfterFunction`` brace wrapping mode is
- /// set, and the function could/should not be put on a single line (as per
- /// ``AllowShortFunctionsOnASingleLine`` and constructor formatting
- /// options).
- /// \code
- /// false: true:
- /// int f() vs. int f()
- /// {} {
- /// }
- /// \endcode
- ///
- bool SplitEmptyFunction;
- /// If ``false``, empty record (e.g. class, struct or union) body
- /// can be put on a single line. This option is used only if the opening
- /// brace of the record has already been wrapped, i.e. the ``AfterClass``
- /// (for classes) brace wrapping mode is set.
- /// \code
- /// false: true:
- /// class Foo vs. class Foo
- /// {} {
- /// }
- /// \endcode
- ///
- bool SplitEmptyRecord;
- /// If ``false``, empty namespace body can be put on a single line.
- /// This option is used only if the opening brace of the namespace has
- /// already been wrapped, i.e. the ``AfterNamespace`` brace wrapping mode is
- /// set.
- /// \code
- /// false: true:
- /// namespace Foo vs. namespace Foo
- /// {} {
- /// }
- /// \endcode
- ///
- bool SplitEmptyNamespace;
- };
-
- /// Control of individual brace wrapping cases.
- ///
- /// If ``BreakBeforeBraces`` is set to ``Custom``, use this to specify how
- /// each individual brace case should be handled. Otherwise, this is ignored.
- /// \code{.yaml}
- /// # Example of usage:
- /// BreakBeforeBraces: Custom
- /// BraceWrapping:
- /// AfterEnum: true
- /// AfterStruct: false
- /// SplitEmptyFunction: false
- /// \endcode
- /// \version 3.8
- BraceWrappingFlags BraceWrapping;
-
- /// Break between adjacent string literals.
- /// \code
- /// true:
- /// return "Code"
- /// "\0\52\26\55\55\0"
- /// "x013"
- /// "\02\xBA";
- /// false:
- /// return "Code" "\0\52\26\55\55\0" "x013" "\02\xBA";
- /// \endcode
- /// \version 18
- bool BreakAdjacentStringLiterals;
-
- /// Different ways to break after the last attribute of a group before a
- /// declaration or control statement.
- enum AttributeBreakingStyle : int8_t {
- /// Always break after the last attribute of the group.
- /// \code
- /// [[maybe_unused]]
- /// const int i;
- /// [[gnu::const]] [[maybe_unused]]
- /// int j;
- ///
- /// [[nodiscard]]
- /// inline int f();
- /// [[gnu::const]] [[nodiscard]]
- /// int g();
- ///
- /// [[likely]]
- /// if (a)
- /// f();
- /// else
- /// g();
- ///
- /// switch (b) {
- /// [[unlikely]]
- /// case 1:
- /// ++b;
- /// break;
- /// [[likely]]
- /// default:
- /// return;
- /// }
- /// \endcode
- ABS_Always,
- /// Leave the line breaking after the last attribute of the group as is.
- /// \code
- /// [[maybe_unused]] const int i;
- /// [[gnu::const]] [[maybe_unused]]
- /// int j;
- ///
- /// [[nodiscard]] inline int f();
- /// [[gnu::const]] [[nodiscard]]
- /// int g();
- ///
- /// [[likely]] if (a)
- /// f();
- /// else
- /// g();
- ///
- /// switch (b) {
- /// [[unlikely]] case 1:
- /// ++b;
- /// break;
- /// [[likely]]
- /// default:
- /// return;
- /// }
- /// \endcode
- ABS_Leave,
- /// Same as ``Leave`` except that it applies to all attributes of the group.
- /// \code
- /// [[deprecated("Don't use this version")]]
- /// [[nodiscard]]
- /// bool foo() {
- /// return true;
- /// }
- ///
- /// [[deprecated("Don't use this version")]]
- /// [[nodiscard]] bool bar() {
- /// return true;
- /// }
- /// \endcode
- ABS_LeaveAll,
- /// Never break after the last attribute of the group.
- /// \code
- /// [[maybe_unused]] const int i;
- /// [[gnu::const]] [[maybe_unused]] int j;
- ///
- /// [[nodiscard]] inline int f();
- /// [[gnu::const]] [[nodiscard]] int g();
- ///
- /// [[likely]] if (a)
- /// f();
- /// else
- /// g();
- ///
- /// switch (b) {
- /// [[unlikely]] case 1:
- /// ++b;
- /// break;
- /// [[likely]] default:
- /// return;
- /// }
- /// \endcode
- ABS_Never,
- };
-
- /// Break after a group of C++11 attributes before variable or function
- /// (including constructor/destructor) declaration/definition names or before
- /// control statements, i.e. ``if``, ``switch`` (including ``case`` and
- /// ``default`` labels), ``for``, and ``while`` statements.
- /// \version 16
- AttributeBreakingStyle BreakAfterAttributes;
-
- /// Force break after the left bracket of a braced initializer list (when
- /// ``Cpp11BracedListStyle`` is ``true``) when the list exceeds the column
- /// limit.
- /// \code
- /// true: false:
- /// vector<int> x { vs. vector<int> x {1,
- /// 1, 2, 3} 2, 3}
- /// \endcode
- /// \version 22
- bool BreakAfterOpenBracketBracedList;
-
- /// Force break after the left parenthesis of a function (declaration,
- /// definition, call) when the parameters exceed the column limit.
- /// \code
- /// true: false:
- /// foo ( vs. foo (a,
- /// a , b) b)
- /// \endcode
- /// \version 22
- bool BreakAfterOpenBracketFunction;
-
- /// Force break after the left parenthesis of an if control statement
- /// when the expression exceeds the column limit.
- /// \code
- /// true: false:
- /// if constexpr ( vs. if constexpr (a ||
- /// a || b) b)
- /// \endcode
- /// \version 22
- bool BreakAfterOpenBracketIf;
-
- /// Force break after the left parenthesis of a loop control statement
- /// when the expression exceeds the column limit.
- /// \code
- /// true: false:
- /// while ( vs. while (a &&
- /// a && b) { b) {
- /// \endcode
- /// \version 22
- bool BreakAfterOpenBracketLoop;
-
- /// Force break after the left parenthesis of a switch control statement
- /// when the expression exceeds the column limit.
- /// \code
- /// true: false:
- /// switch ( vs. switch (a +
- /// a + b) { b) {
- /// \endcode
- /// \version 22
- bool BreakAfterOpenBracketSwitch;
-
- /// The function declaration return type breaking style to use.
- /// \version 19
- ReturnTypeBreakingStyle BreakAfterReturnType;
-
- /// If ``true``, clang-format will always break after a Json array ``[``
- /// otherwise it will scan until the closing ``]`` to determine if it should
- /// add newlines between elements (prettier compatible).
- ///
- /// \note
- /// This is currently only for formatting JSON.
- /// \endnote
- /// \code
- /// true: false:
- /// [ vs. [1, 2, 3, 4]
- /// 1,
- /// 2,
- /// 3,
- /// 4
- /// ]
- /// \endcode
- /// \version 16
- bool BreakArrays;
-
- /// The style of wrapping parameters on the same line (bin-packed) or
- /// on one line each.
- enum BinPackStyle : int8_t {
- /// Automatically determine parameter bin-packing behavior.
- BPS_Auto,
- /// Always bin-pack parameters.
- BPS_Always,
- /// Never bin-pack parameters.
- BPS_Never,
- };
-
- /// The style of breaking before or after binary operators.
- enum BinaryOperatorStyle : int8_t {
- /// Break after operators.
- /// \code
- /// LooooooooooongType loooooooooooooooooooooongVariable =
- /// someLooooooooooooooooongFunction();
- ///
- /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
- /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
- /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
- /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
- /// ccccccccccccccccccccccccccccccccccccccccc;
- /// \endcode
- BOS_None,
- /// Break before operators that aren't assignments.
- /// \code
- /// LooooooooooongType loooooooooooooooooooooongVariable =
- /// someLooooooooooooooooongFunction();
- ///
- /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// > ccccccccccccccccccccccccccccccccccccccccc;
- /// \endcode
- BOS_NonAssignment,
- /// Break before operators.
- /// \code
- /// LooooooooooongType loooooooooooooooooooooongVariable
- /// = someLooooooooooooooooongFunction();
- ///
- /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- /// > ccccccccccccccccccccccccccccccccccccccccc;
- /// \endcode
- BOS_All,
- };
-
- /// The way to wrap binary operators.
- /// \version 3.6
- BinaryOperatorStyle BreakBeforeBinaryOperators;
-
- /// Different ways to attach braces to their surrounding context.
- enum BraceBreakingStyle : int8_t {
- /// Always attach braces to surrounding context.
- /// \code
- /// namespace N {
- /// enum E {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i) {
- /// try {
- /// do {
- /// switch (i) {
- /// case 1: {
- /// foobar();
- /// break;
- /// }
- /// default: {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// } catch (...) {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b) {
- /// if (b) {
- /// baz(2);
- /// } else {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Attach,
- /// Like ``Attach``, but break before braces on function, namespace and
- /// class definitions.
- /// \code
- /// namespace N
- /// {
- /// enum E {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C
- /// {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try {
- /// do {
- /// switch (i) {
- /// case 1: {
- /// foobar();
- /// break;
- /// }
- /// default: {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// } catch (...) {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b) {
- /// baz(2);
- /// } else {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Linux,
- /// Like ``Attach``, but break before braces on enum, function, and record
- /// definitions.
- /// \code
- /// namespace N {
- /// enum E
- /// {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C
- /// {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try {
- /// do {
- /// switch (i) {
- /// case 1: {
- /// foobar();
- /// break;
- /// }
- /// default: {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// } catch (...) {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b) {
- /// baz(2);
- /// } else {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Mozilla,
- /// Like ``Attach``, but break before function definitions, ``catch``, and
- /// ``else``.
- /// \code
- /// namespace N {
- /// enum E {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try {
- /// do {
- /// switch (i) {
- /// case 1: {
- /// foobar();
- /// break;
- /// }
- /// default: {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// }
- /// catch (...) {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b) {
- /// baz(2);
- /// }
- /// else {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Stroustrup,
- /// Always break before braces.
- /// \code
- /// namespace N
- /// {
- /// enum E
- /// {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C
- /// {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try
- /// {
- /// do
- /// {
- /// switch (i)
- /// {
- /// case 1:
- /// {
- /// foobar();
- /// break;
- /// }
- /// default:
- /// {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// }
- /// catch (...)
- /// {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b)
- /// {
- /// baz(2);
- /// }
- /// else
- /// {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Allman,
- /// Like ``Allman`` but always indent braces and line up code with braces.
- /// \code
- /// namespace N
- /// {
- /// enum E
- /// {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C
- /// {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try
- /// {
- /// do
- /// {
- /// switch (i)
- /// {
- /// case 1:
- /// {
- /// foobar();
- /// break;
- /// }
- /// default:
- /// {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// }
- /// catch (...)
- /// {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b)
- /// {
- /// baz(2);
- /// }
- /// else
- /// {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_Whitesmiths,
- /// Always break before braces and add an extra level of indentation to
- /// braces of control statements, not to those of class, function
- /// or other definitions.
- /// \code
- /// namespace N
- /// {
- /// enum E
- /// {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C
- /// {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try
- /// {
- /// do
- /// {
- /// switch (i)
- /// {
- /// case 1:
- /// {
- /// foobar();
- /// break;
- /// }
- /// default:
- /// {
- /// break;
- /// }
- /// }
- /// }
- /// while (--i);
- /// return true;
- /// }
- /// catch (...)
- /// {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b)
- /// {
- /// baz(2);
- /// }
- /// else
- /// {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_GNU,
- /// Like ``Attach``, but break before functions.
- /// \code
- /// namespace N {
- /// enum E {
- /// E1,
- /// E2,
- /// };
- ///
- /// class C {
- /// public:
- /// C();
- /// };
- ///
- /// bool baz(int i)
- /// {
- /// try {
- /// do {
- /// switch (i) {
- /// case 1: {
- /// foobar();
- /// break;
- /// }
- /// default: {
- /// break;
- /// }
- /// }
- /// } while (--i);
- /// return true;
- /// } catch (...) {
- /// handleError();
- /// return false;
- /// }
- /// }
- ///
- /// void foo(bool b)
- /// {
- /// if (b) {
- /// baz(2);
- /// } else {
- /// baz(5);
- /// }
- /// }
- ///
- /// void bar() { foo(true); }
- /// } // namespace N
- /// \endcode
- BS_WebKit,
- /// Configure each individual brace in ``BraceWrapping``.
- BS_Custom
- };
-
- /// The brace breaking style to use.
- /// \version 3.7
- BraceBreakingStyle BreakBeforeBraces;
-
- /// Force break before the right bracket of a braced initializer list (when
- /// ``Cpp11BracedListStyle`` is ``true``) when the list exceeds the column
- /// limit. The break before the right bracket is only made if there is a
- /// break after the opening bracket.
- /// \code
- /// true: false:
- /// vector<int> x { vs. vector<int> x {
- /// 1, 2, 3 1, 2, 3}
- /// }
- /// \endcode
- /// \version 22
- bool BreakBeforeCloseBracketBracedList;
-
- /// Force break before the right parenthesis of a function (declaration,
- /// definition, call) when the parameters exceed the column limit.
- /// \code
- /// true: false:
- /// foo ( vs. foo (
- /// a , b a , b)
- /// )
- /// \endcode
- /// \version 22
- bool BreakBeforeCloseBracketFunction;
-
- /// Force break before the right parenthesis of an if control statement
- /// when the expression exceeds the column limit. The break before the
- /// closing parenthesis is only made if there is a break after the opening
- /// parenthesis.
- /// \code
- /// true: false:
- /// if constexpr ( vs. if constexpr (
- /// a || b a || b )
- /// )
- /// \endcode
- /// \version 22
- bool BreakBeforeCloseBracketIf;
-
- /// Force break before the right parenthesis of a loop control statement
- /// when the expression exceeds the column limit. The break before the
- /// closing parenthesis is only made if there is a break after the opening
- /// parenthesis.
- /// \code
- /// true: false:
- /// while ( vs. while (
- /// a && b a && b) {
- /// ) {
- /// \endcode
- /// \version 22
- bool BreakBeforeCloseBracketLoop;
-
- /// Force break before the right parenthesis of a switch control statement
- /// when the expression exceeds the column limit. The break before the
- /// closing parenthesis is only made if there is a break after the opening
- /// parenthesis.
- /// \code
- /// true: false:
- /// switch ( vs. switch (
- /// a + b a + b) {
- /// ) {
- /// \endcode
- /// \version 22
- bool BreakBeforeCloseBracketSwitch;
-
- /// Different ways to break before concept declarations.
- enum BreakBeforeConceptDeclarationsStyle : int8_t {
- /// Keep the template declaration line together with ``concept``.
- /// \code
- /// template <typename T> concept C = ...;
- /// \endcode
- BBCDS_Never,
- /// Breaking between template declaration and ``concept`` is allowed. The
- /// actual behavior depends on the content and line breaking rules and
- /// penalties.
- BBCDS_Allowed,
- /// Always break before ``concept``, putting it in the line after the
- /// template declaration.
- /// \code
- /// template <typename T>
- /// concept C = ...;
- /// \endcode
- BBCDS_Always,
- };
-
- /// The concept declaration style to use.
- /// \version 12
- BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations;
-
- /// Different ways to break ASM parameters.
- enum BreakBeforeInlineASMColonStyle : int8_t {
- /// No break before inline ASM colon.
- /// \code
- /// asm volatile("string", : : val);
- /// \endcode
- BBIAS_Never,
- /// Break before inline ASM colon if the line length is longer than column
- /// limit.
- /// \code
- /// asm volatile("string", : : val);
- /// asm("cmoveq %1, %2, %[result]"
- /// : [result] "=r"(result)
- /// : "r"(test), "r"(new), "[result]"(old));
- /// \endcode
- BBIAS_OnlyMultiline,
- /// Always break before inline ASM colon.
- /// \code
- /// asm volatile("string",
- /// :
- /// : val);
- /// \endcode
- BBIAS_Always,
- };
-
- /// The inline ASM colon style to use.
- /// \version 16
- BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
-
- /// If ``true``, break before a template closing bracket (``>``) when there is
- /// a line break after the matching opening bracket (``<``).
- /// \code
- /// true:
- /// template <typename Foo, typename Bar>
- ///
- /// template <typename Foo,
- /// typename Bar>
- ///
- /// template <
- /// typename Foo,
- /// typename Bar
- /// >
- ///
- /// false:
- /// template <typename Foo, typename Bar>
- ///
- /// template <typename Foo,
- /// typename Bar>
- ///
- /// template <
- /// typename Foo,
- /// typename Bar>
- /// \endcode
- /// \version 21
- bool BreakBeforeTemplateCloser;
-
- /// If ``true``, ternary operators will be placed after line breaks.
- /// \code
- /// true:
- /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
- /// ? firstValue
- /// : SecondValueVeryVeryVeryVeryLong;
- ///
- /// false:
- /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
- /// firstValue :
- /// SecondValueVeryVeryVeryVeryLong;
- /// \endcode
- /// \version 3.7
- bool BreakBeforeTernaryOperators;
-
- /// Different ways to break binary operations.
- enum BreakBinaryOperationsStyle : int8_t {
- /// Don't break binary operations
- /// \code
- /// aaa + bbbb * ccccc - ddddd +
- /// eeeeeeeeeeeeeeee;
- /// \endcode
- BBO_Never,
-
- /// Binary operations will either be all on the same line, or each operation
- /// will have one line each.
- /// \code
- /// aaa +
- /// bbbb *
- /// ccccc -
- /// ddddd +
- /// eeeeeeeeeeeeeeee;
- /// \endcode
- BBO_OnePerLine,
-
- /// Binary operations of a particular precedence that exceed the column
- /// limit will have one line each.
- /// \code
- /// aaa +
- /// bbbb * ccccc -
- /// ddddd +
- /// eeeeeeeeeeeeeeee;
- /// \endcode
- BBO_RespectPrecedence
- };
-
- /// A rule that specifies how to break a specific set of binary operators.
- /// \version 23
- struct BinaryOperationBreakRule {
- /// The list of operators this rule applies to, e.g. ``&&``, ``||``, ``|``.
- /// Alternative spellings (e.g. ``and`` for ``&&``) are accepted.
- std::vector<tok::TokenKind> Operators;
- /// The break style for these operators (defaults to ``OnePerLine``).
- BreakBinaryOperationsStyle Style;
- /// Minimum number of operands in a chain before the rule triggers.
- /// For example, ``a && b && c`` is a chain of length 3.
- /// ``0`` means always break (when the line is too long).
- unsigned MinChainLength;
- bool operator==(const BinaryOperationBreakRule &R) const {
- return Operators == R.Operators && Style == R.Style &&
- MinChainLength == R.MinChainLength;
- }
- bool operator!=(const BinaryOperationBreakRule &R) const {
- return !(*this == R);
- }
- };
-
- /// Options for ``BreakBinaryOperations``.
- ///
- /// If specified as a simple string (e.g. ``OnePerLine``), it behaves like
- /// the original enum and applies to all binary operators.
- ///
- /// If specified as a struct, allows per-operator configuration:
- /// \code{.yaml}
- /// BreakBinaryOperations:
- /// Default: Never
- /// PerOperator:
- /// - Operators: ['&&', '||']
- /// Style: OnePerLine
- /// MinChainLength: 3
- /// \endcode
- /// \version 23
- struct BreakBinaryOperationsOptions {
- /// The default break style for operators not covered by ``PerOperator``.
- BreakBinaryOperationsStyle Default;
- /// Per-operator override rules.
- std::vector<BinaryOperationBreakRule> PerOperator;
- const BinaryOperationBreakRule *
- findRuleForOperator(tok::TokenKind Kind) const {
- for (const auto &Rule : PerOperator) {
- if (llvm::find(Rule.Operators, Kind) != Rule.Operators.end())
- return &Rule;
- // clang-format splits ">>" into two ">" tokens for template parsing.
- // Match ">" against ">>" rules so that per-operator rules for ">>"
- // (stream extraction / right shift) work correctly.
- if (Kind == tok::greater &&
- llvm::find(Rule.Operators, tok::greatergreater) !=
- Rule.Operators.end()) {
- return &Rule;
- }
- }
- return nullptr;
- }
- BreakBinaryOperationsStyle getStyleForOperator(tok::TokenKind Kind) const {
- if (const auto *Rule = findRuleForOperator(Kind))
- return Rule->Style;
- return Default;
- }
- unsigned getMinChainLengthForOperator(tok::TokenKind Kind) const {
- if (const auto *Rule = findRuleForOperator(Kind))
- return Rule->MinChainLength;
- return 0;
- }
- bool operator==(const BreakBinaryOperationsOptions &R) const {
- return Default == R.Default && PerOperator == R.PerOperator;
- }
- bool operator!=(const BreakBinaryOperationsOptions &R) const {
- return !(*this == R);
- }
- };
-
- /// The break binary operations style to use.
- /// \version 20
- BreakBinaryOperationsOptions BreakBinaryOperations;
-
- /// Different ways to break initializers.
- enum BreakConstructorInitializersStyle : int8_t {
- /// Break constructor initializers before the colon and after the commas.
- /// \code
- /// Constructor()
- /// : initializer1(),
- /// initializer2()
- /// \endcode
- BCIS_BeforeColon,
- /// Break constructor initializers before the colon and commas, and align
- /// the commas with the colon.
- /// \code
- /// Constructor()
- /// : initializer1()
- /// , initializer2()
- /// \endcode
- BCIS_BeforeComma,
- /// Break constructor initializers after the colon and commas.
- /// \code
- /// Constructor() :
- /// initializer1(),
- /// initializer2()
- /// \endcode
- BCIS_AfterColon,
- /// Break constructor initializers only after the commas.
- /// \code
- /// Constructor() : initializer1(),
- /// initializer2()
- /// \endcode
- BCIS_AfterComma
- };
-
- /// The break constructor initializers style to use.
- /// \version 5
- BreakConstructorInitializersStyle BreakConstructorInitializers;
-
- /// If ``true``, clang-format will always break before function definition
- /// parameters.
- /// \code
- /// true:
- /// void functionDefinition(
- /// int A, int B) {}
- ///
- /// false:
- /// void functionDefinition(int A, int B) {}
- ///
- /// \endcode
- /// \version 19
- bool BreakFunctionDefinitionParameters;
-
- /// Break after each annotation on a field in Java files.
- /// \code{.java}
- /// true: false:
- /// @Partial vs. @Partial @Mock DataLoad loader;
- /// @Mock
- /// DataLoad loader;
- /// \endcode
- /// \version 3.8
- bool BreakAfterJavaFieldAnnotations;
-
- /// Allow breaking string literals when formatting.
- ///
- /// In C, C++, and Objective-C:
- /// \code
- /// true:
- /// const char* x = "veryVeryVeryVeryVeryVe"
- /// "ryVeryVeryVeryVeryVery"
- /// "VeryLongString";
- ///
- /// false:
- /// const char* x =
- /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
- /// \endcode
- ///
- /// In C# and Java:
- /// \code
- /// true:
- /// string x = "veryVeryVeryVeryVeryVe" +
- /// "ryVeryVeryVeryVeryVery" +
- /// "VeryLongString";
- ///
- /// false:
- /// string x =
- /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
- /// \endcode
- ///
- /// C# interpolated strings are not broken.
- ///
- /// In Verilog:
- /// \code
- /// true:
- /// string x = {"veryVeryVeryVeryVeryVe",
- /// "ryVeryVeryVeryVeryVery",
- /// "VeryLongString"};
- ///
- /// false:
- /// string x =
- /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
- /// \endcode
- ///
- /// \version 3.9
- bool BreakStringLiterals;
-
- /// The column limit.
- ///
- /// A column limit of ``0`` means that there is no column limit. In this case,
- /// clang-format will respect the input's line breaking decisions within
- /// statements unless they contradict other rules.
- /// \version 3.7
- unsigned ColumnLimit;
-
- /// A regular expression that describes comments with special meaning,
- /// which should not be split into lines or otherwise changed.
- /// \code
- /// // CommentPragmas: '^ FOOBAR pragma:'
- /// // Will leave the following line unaffected
- /// #include <vector> // FOOBAR pragma: keep
- /// \endcode
- /// \version 3.7
- std::string CommentPragmas;
-
- /// Different ways to break inheritance list.
- enum BreakInheritanceListStyle : int8_t {
- /// Break inheritance list before the colon and after the commas.
- /// \code
- /// class Foo
- /// : Base1,
- /// Base2
- /// {};
- /// \endcode
- BILS_BeforeColon,
- /// Break inheritance list before the colon and commas, and align
- /// the commas with the colon.
- /// \code
- /// class Foo
- /// : Base1
- /// , Base2
- /// {};
- /// \endcode
- BILS_BeforeComma,
- /// Break inheritance list after the colon and commas.
- /// \code
- /// class Foo :
- /// Base1,
- /// Base2
- /// {};
- /// \endcode
- BILS_AfterColon,
- /// Break inheritance list only after the commas.
- /// \code
- /// class Foo : Base1,
- /// Base2
- /// {};
- /// \endcode
- BILS_AfterComma,
- };
-
- /// The inheritance list style to use.
- /// \version 7
- BreakInheritanceListStyle BreakInheritanceList;
-
- /// The template declaration breaking style to use.
- /// \version 19
- BreakTemplateDeclarationsStyle BreakTemplateDeclarations;
-
- /// If ``true``, consecutive namespace declarations will be on the same
- /// line. If ``false``, each namespace is declared on a new line.
- /// \code
- /// true:
- /// namespace Foo { namespace Bar {
- /// }}
- ///
- /// false:
- /// namespace Foo {
- /// namespace Bar {
- /// }
- /// }
- /// \endcode
- ///
- /// If it does not fit on a single line, the overflowing namespaces get
- /// wrapped:
- /// \code
- /// namespace Foo { namespace Bar {
- /// namespace Extra {
- /// }}}
- /// \endcode
- /// \version 5
- bool CompactNamespaces;
-
- /// This option is **deprecated**. See ``CurrentLine`` of
- /// ``PackConstructorInitializers``.
- /// \version 3.7
- // bool ConstructorInitializerAllOnOneLineOrOnePerLine;
-
- /// The number of characters to use for indentation of constructor
- /// initializer lists as well as inheritance lists.
- /// \version 3.7
- unsigned ConstructorInitializerIndentWidth;
-
- /// Indent width for line continuations.
- /// \code
- /// ContinuationIndentWidth: 2
- ///
- /// int i = // VeryVeryVeryVeryVeryLongComment
- /// longFunction( // Again a long comment
- /// arg);
- /// \endcode
- /// \version 3.7
- unsigned ContinuationIndentWidth;
-
- /// Different ways to handle braced lists.
- enum BracedListStyle : int8_t {
- /// Best suited for pre C++11 braced lists.
- ///
- /// * Spaces inside the braced list.
- /// * Line break before the closing brace.
- /// * Indentation with the block indent.
- ///
- /// \code
- /// vector<int> x{ 1, 2, 3, 4 };
- /// vector<T> x{ {}, {}, {}, {} };
- /// f(MyMap[{ composite, key }]);
- /// new int[3]{ 1, 2, 3 };
- /// Type name{ // Comment
- /// value
- /// };
- /// \endcode
- BLS_Block,
- /// Best suited for C++11 braced lists.
- ///
- /// * No spaces inside the braced list.
- /// * No line break before the closing brace.
- /// * Indentation with the continuation indent.
- ///
- /// Fundamentally, C++11 braced lists are formatted exactly like function
- /// calls would be formatted in their place. If the braced list follows a
- /// name (e.g. a type or variable name), clang-format formats as if the
- /// ``{}`` were the parentheses of a function call with that name. If there
- /// is no name, a zero-length name is assumed.
- /// \code
- /// vector<int> x{1, 2, 3, 4};
- /// vector<T> x{{}, {}, {}, {}};
- /// f(MyMap[{composite, key}]);
- /// new int[3]{1, 2, 3};
- /// Type name{ // Comment
- /// value};
- /// \endcode
- BLS_FunctionCall,
- /// Same as ``FunctionCall``, except for the handling of a comment at the
- /// begin, it then aligns everything following with the comment.
- ///
- /// * No spaces inside the braced list. (Even for a comment at the first
- /// position.)
- /// * No line break before the closing brace.
- /// * Indentation with the continuation indent, except when followed by a
- /// line comment, then it uses the block indent.
- ///
- /// \code
- /// vector<int> x{1, 2, 3, 4};
- /// vector<T> x{{}, {}, {}, {}};
- /// f(MyMap[{composite, key}]);
- /// new int[3]{1, 2, 3};
- /// Type name{// Comment
- /// value};
- /// \endcode
- BLS_AlignFirstComment,
- };
-
- /// The style to handle braced lists.
- /// \version 3.4
- BracedListStyle Cpp11BracedListStyle;
-
- /// This option is **deprecated**. See ``DeriveLF`` and ``DeriveCRLF`` of
- /// ``LineEnding``.
- /// \version 10
- // bool DeriveLineEnding;
-
- /// If ``true``, analyze the formatted file for the most common
- /// alignment of ``&`` and ``*``.
- /// Pointer and reference alignment styles are going to be updated according
- /// to the preferences found in the file.
- /// ``PointerAlignment`` is then used only as fallback.
- /// \version 3.7
- bool DerivePointerAlignment;
-
- /// Disables formatting completely.
- /// \version 3.7
- bool DisableFormat;
-
- /// Different styles for empty line after access modifiers.
- /// ``EmptyLineBeforeAccessModifier`` configuration handles the number of
- /// empty lines between two access modifiers.
- enum EmptyLineAfterAccessModifierStyle : int8_t {
- /// Remove all empty lines after access modifiers.
- /// \code
- /// struct foo {
- /// private:
- /// int i;
- /// protected:
- /// int j;
- /// /* comment */
- /// public:
- /// foo() {}
- /// private:
- /// protected:
- /// };
- /// \endcode
- ELAAMS_Never,
- /// Keep existing empty lines after access modifiers.
- /// MaxEmptyLinesToKeep is applied instead.
- ELAAMS_Leave,
- /// Always add empty line after access modifiers if there are none.
- /// MaxEmptyLinesToKeep is applied also.
- /// \code
- /// struct foo {
- /// private:
- ///
- /// int i;
- /// protected:
- ///
- /// int j;
- /// /* comment */
- /// public:
- ///
- /// foo() {}
- /// private:
- ///
- /// protected:
- ///
- /// };
- /// \endcode
- ELAAMS_Always,
- };
-
- /// Defines when to put an empty line after access modifiers.
- /// ``EmptyLineBeforeAccessModifier`` configuration handles the number of
- /// empty lines between two access modifiers.
- /// \version 13
- EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier;
-
- /// Different styles for empty line before access modifiers.
- enum EmptyLineBeforeAccessModifierStyle : int8_t {
- /// Remove all empty lines before access modifiers.
- /// \code
- /// struct foo {
- /// private:
- /// int i;
- /// protected:
- /// int j;
- /// /* comment */
- /// public:
- /// foo() {}
- /// private:
- /// protected:
- /// };
- /// \endcode
- ELBAMS_Never,
- /// Keep existing empty lines before access modifiers.
- ELBAMS_Leave,
- /// Add empty line only when access modifier starts a new logical block.
- /// Logical block is a group of one or more member fields or functions.
- /// \code
- /// struct foo {
- /// private:
- /// int i;
- ///
- /// protected:
- /// int j;
- /// /* comment */
- /// public:
- /// foo() {}
- ///
- /// private:
- /// protected:
- /// };
- /// \endcode
- ELBAMS_LogicalBlock,
- /// Always add empty line before access modifiers unless access modifier
- /// is at the start of struct or class definition.
- /// \code
- /// struct foo {
- /// private:
- /// int i;
- ///
- /// protected:
- /// int j;
- /// /* comment */
- ///
- /// public:
- /// foo() {}
- ///
- /// private:
- ///
- /// protected:
- /// };
- /// \endcode
- ELBAMS_Always,
- };
-
- /// Defines in which cases to put empty line before access modifiers.
- /// \version 12
- EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
-
- /// Styles for ``enum`` trailing commas.
- enum EnumTrailingCommaStyle : int8_t {
- /// Don't insert or remove trailing commas.
- /// \code
- /// enum { a, b, c, };
- /// enum Color { red, green, blue };
- /// \endcode
- ETC_Leave,
- /// Insert trailing commas.
- /// \code
- /// enum { a, b, c, };
- /// enum Color { red, green, blue, };
- /// \endcode
- ETC_Insert,
- /// Remove trailing commas.
- /// \code
- /// enum { a, b, c };
- /// enum Color { red, green, blue };
- /// \endcode
- ETC_Remove,
- };
-
- /// Insert a comma (if missing) or remove the comma at the end of an ``enum``
- /// enumerator list.
- /// \warning
- /// Setting this option to any value other than ``Leave`` could lead to
- /// incorrect code formatting due to clang-format's lack of complete semantic
- /// information. As such, extra care should be taken to review code changes
- /// made by this option.
- /// \endwarning
- /// \version 21
- EnumTrailingCommaStyle EnumTrailingComma;
-
- /// If ``true``, clang-format detects whether function calls and
- /// definitions are formatted with one parameter per line.
- ///
- /// Each call can be bin-packed, one-per-line or inconclusive. If it is
- /// inconclusive, e.g. completely on one line, but a decision needs to be
- /// made, clang-format analyzes whether there are other bin-packed cases in
- /// the input file and act accordingly.
- ///
- /// \note
- /// This is an experimental flag, that might go away or be renamed. Do
- /// not use this in config files, etc. Use at your own risk.
- /// \endnote
- /// \version 3.7
- bool ExperimentalAutoDetectBinPacking;
-
- /// If ``true``, clang-format adds missing namespace end comments for
- /// namespaces and fixes invalid existing ones. This doesn't affect short
- /// namespaces, which are controlled by ``ShortNamespaceLines``.
- /// \code
- /// true: false:
- /// namespace longNamespace { vs. namespace longNamespace {
- /// void foo(); void foo();
- /// void bar(); void bar();
- /// } // namespace a }
- /// namespace shortNamespace { namespace shortNamespace {
- /// void baz(); void baz();
- /// } }
- /// \endcode
- /// \version 5
- bool FixNamespaceComments;
-
- /// A vector of macros that should be interpreted as foreach loops
- /// instead of as function calls.
- ///
- /// These are expected to be macros of the form:
- /// \code
- /// FOREACH(<variable-declaration>, ...)
- /// <loop-body>
- /// \endcode
- ///
- /// In the .clang-format configuration file, this can be configured like:
- /// \code{.yaml}
- /// ForEachMacros: [RANGES_FOR, FOREACH]
- /// \endcode
- ///
- /// For example: BOOST_FOREACH.
- /// \version 3.7
- std::vector<std::string> ForEachMacros;
-
- tooling::IncludeStyle IncludeStyle;
-
- /// A vector of macros that should be interpreted as conditionals
- /// instead of as function calls.
- ///
- /// These are expected to be macros of the form:
- /// \code
- /// IF(...)
- /// <conditional-body>
- /// else IF(...)
- /// <conditional-body>
- /// \endcode
- ///
- /// In the .clang-format configuration file, this can be configured like:
- /// \code{.yaml}
- /// IfMacros: [IF]
- /// \endcode
- ///
- /// For example: `KJ_IF_MAYBE
- /// <https://github.com/capnproto/capnproto/blob/master/kjdoc/tour.md#maybes>`_
- /// \version 13
- std::vector<std::string> IfMacros;
-
- /// Specify whether access modifiers should have their own indentation level.
- ///
- /// When ``false``, access modifiers are indented (or outdented) relative to
- /// the record members, respecting the ``AccessModifierOffset``. Record
- /// members are indented one level below the record.
- /// When ``true``, access modifiers get their own indentation level. As a
- /// consequence, record members are always indented 2 levels below the record,
- /// regardless of the access modifier presence. Value of the
- /// ``AccessModifierOffset`` is ignored.
- /// \code
- /// false: true:
- /// class C { vs. class C {
- /// class D { class D {
- /// void bar(); void bar();
- /// protected: protected:
- /// D(); D();
- /// }; };
- /// public: public:
- /// C(); C();
- /// }; };
- /// void foo() { void foo() {
- /// return 1; return 1;
- /// } }
- /// \endcode
- /// \version 13
- bool IndentAccessModifiers;
-
- /// Indent case label blocks one level from the case label.
- ///
- /// When ``false``, the block following the case label uses the same
- /// indentation level as for the case label, treating the case label the same
- /// as an if-statement.
- /// When ``true``, the block gets indented as a scope block.
- /// \code
- /// false: true:
- /// switch (fool) { vs. switch (fool) {
- /// case 1: { case 1:
- /// bar(); {
- /// } break; bar();
- /// default: { }
- /// plop(); break;
- /// } default:
- /// } {
- /// plop();
- /// }
- /// }
- /// \endcode
- /// \version 11
- bool IndentCaseBlocks;
-
- /// Indent case labels one level from the switch statement.
- ///
- /// When ``false``, use the same indentation level as for the switch
- /// statement. Switch statement body is always indented one level more than
- /// case labels (except the first block following the case label, which
- /// itself indents the code - unless IndentCaseBlocks is enabled).
- /// \code
- /// false: true:
- /// switch (fool) { vs. switch (fool) {
- /// case 1: case 1:
- /// bar(); bar();
- /// break; break;
- /// default: default:
- /// plop(); plop();
- /// } }
- /// \endcode
- /// \version 3.3
- bool IndentCaseLabels;
-
- /// If ``true``, clang-format will indent the body of an ``export { ... }``
- /// block. This doesn't affect the formatting of anything else related to
- /// exported declarations.
- /// \code
- /// true: false:
- /// export { vs. export {
- /// void foo(); void foo();
- /// void bar(); void bar();
- /// } }
- /// \endcode
- /// \version 20
- bool IndentExportBlock;
-
- /// Indents extern blocks
- enum IndentExternBlockStyle : int8_t {
- /// Backwards compatible with AfterExternBlock's indenting.
- /// \code
- /// IndentExternBlock: AfterExternBlock
- /// BraceWrapping.AfterExternBlock: true
- /// extern "C"
- /// {
- /// void foo();
- /// }
- /// \endcode
- ///
- /// \code
- /// IndentExternBlock: AfterExternBlock
- /// BraceWrapping.AfterExternBlock: false
- /// extern "C" {
- /// void foo();
- /// }
- /// \endcode
- IEBS_AfterExternBlock,
- /// Does not indent extern blocks.
- /// \code
- /// extern "C" {
- /// void foo();
- /// }
- /// \endcode
- IEBS_NoIndent,
- /// Indents extern blocks.
- /// \code
- /// extern "C" {
- /// void foo();
- /// }
- /// \endcode
- IEBS_Indent,
- };
-
- /// IndentExternBlockStyle is the type of indenting of extern blocks.
- /// \version 11
- IndentExternBlockStyle IndentExternBlock;
-
- /// Options for indenting goto labels.
- enum IndentGotoLabelStyle : int8_t {
- /// Do not indent goto labels.
- /// \code
- /// int f() {
- /// if (foo()) {
- /// label1:
- /// bar();
- /// }
- /// label2:
- /// return 1;
- /// }
- /// \endcode
- IGLS_NoIndent,
- /// Indent goto labels to the enclosing block (previous indenting level).
- /// \code
- /// int f() {
- /// if (foo()) {
- /// label1:
- /// bar();
- /// }
- /// label2:
- /// return 1;
- /// }
- /// \endcode
- IGLS_OuterIndent,
- /// Indent goto labels to the surrounding statements (current indenting
- /// level).
- /// \code
- /// int f() {
- /// if (foo()) {
- /// label1:
- /// bar();
- /// }
- /// label2:
- /// return 1;
- /// }
- /// \endcode
- IGLS_InnerIndent,
- /// Indent goto labels to half the indentation of the surrounding code.
- /// If the indentation width is an odd number, it will round up.
- /// \code
- /// int f() {
- /// if (foo()) {
- /// label1:
- /// bar();
- /// }
- /// label2:
- /// return 1;
- /// }
- /// \endcode
- IGLS_HalfIndent,
- };
-
- /// The goto label indenting style to use.
- /// \version 10
- IndentGotoLabelStyle IndentGotoLabels;
-
- /// Options for indenting preprocessor directives.
- enum PPDirectiveIndentStyle : int8_t {
- /// Does not indent any directives.
- /// \code
- /// #if FOO
- /// #if BAR
- /// #include <foo>
- /// #endif
- /// #endif
- /// \endcode
- PPDIS_None,
- /// Indents directives after the hash.
- /// \code
- /// #if FOO
- /// # if BAR
- /// # include <foo>
- /// # endif
- /// #endif
- /// \endcode
- PPDIS_AfterHash,
- /// Indents directives before the hash.
- /// \code
- /// #if FOO
- /// #if BAR
- /// #include <foo>
- /// #endif
- /// #endif
- /// \endcode
- PPDIS_BeforeHash,
- /// Leaves indentation of directives as-is.
- /// \note
- /// Ignores ``PPIndentWidth``.
- /// \endnote
- /// \code
- /// #if FOO
- /// #if BAR
- /// #include <foo>
- /// #endif
- /// #endif
- /// \endcode
- PPDIS_Leave
- };
-
- /// The preprocessor directive indenting style to use.
- /// \version 6
- PPDirectiveIndentStyle IndentPPDirectives;
-
- /// Indent the requires clause in a template. This only applies when
- /// ``RequiresClausePosition`` is ``OwnLine``, ``OwnLineWithBrace``,
- /// or ``WithFollowing``.
- ///
- /// In clang-format 12, 13 and 14 it was named ``IndentRequires``.
- /// \code
- /// true:
- /// template <typename It>
- /// requires Iterator<It>
- /// void sort(It begin, It end) {
- /// //....
- /// }
- ///
- /// false:
- /// template <typename It>
- /// requires Iterator<It>
- /// void sort(It begin, It end) {
- /// //....
- /// }
- /// \endcode
- /// \version 15
- bool IndentRequiresClause;
-
- /// The number of columns to use for indentation.
- /// \code
- /// IndentWidth: 3
- ///
- /// void f() {
- /// someFunction();
- /// if (true, false) {
- /// f();
- /// }
- /// }
- /// \endcode
- /// \version 3.7
- unsigned IndentWidth;
-
- /// Indent if a function definition or declaration is wrapped after the
- /// type.
- /// \code
- /// true:
- /// LoooooooooooooooooooooooooooooooooooooooongReturnType
- /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
- ///
- /// false:
- /// LoooooooooooooooooooooooooooooooooooooooongReturnType
- /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
- /// \endcode
- /// \version 3.7
- bool IndentWrappedFunctionNames;
-
- /// Insert braces after control statements (``if``, ``else``, ``for``, ``do``,
- /// and ``while``) in C++ unless the control statements are inside macro
- /// definitions or the braces would enclose preprocessor directives.
- /// \warning
- /// Setting this option to ``true`` could lead to incorrect code formatting
- /// due to clang-format's lack of complete semantic information. As such,
- /// extra care should be taken to review code changes made by this option.
- /// \endwarning
- /// \code
- /// false: true:
- ///
- /// if (isa<FunctionDecl>(D)) vs. if (isa<FunctionDecl>(D)) {
- /// handleFunctionDecl(D); handleFunctionDecl(D);
- /// else if (isa<VarDecl>(D)) } else if (isa<VarDecl>(D)) {
- /// handleVarDecl(D); handleVarDecl(D);
- /// else } else {
- /// return; return;
- /// }
- ///
- /// while (i--) vs. while (i--) {
- /// for (auto *A : D.attrs()) for (auto *A : D.attrs()) {
- /// handleAttr(A); handleAttr(A);
- /// }
- /// }
- ///
- /// do vs. do {
- /// --i; --i;
- /// while (i); } while (i);
- /// \endcode
- /// \version 15
- bool InsertBraces;
-
- /// Insert a newline at end of file if missing.
- /// \version 16
- bool InsertNewlineAtEOF;
-
- /// The style of inserting trailing commas into container literals.
- enum TrailingCommaStyle : int8_t {
- /// Do not insert trailing commas.
- TCS_None,
- /// Insert trailing commas in container literals that were wrapped over
- /// multiple lines. Note that this is conceptually incompatible with
- /// bin-packing, because the trailing comma is used as an indicator
- /// that a container should be formatted one-per-line (i.e. not bin-packed).
- /// So inserting a trailing comma counteracts bin-packing.
- TCS_Wrapped,
- };
-
- /// If set to ``TCS_Wrapped`` will insert trailing commas in container
- /// literals (arrays and objects) that wrap across multiple lines.
- /// It is currently only available for JavaScript
- /// and disabled by default ``TCS_None``.
- /// ``InsertTrailingCommas`` cannot be used together with ``BinPackArguments``
- /// as inserting the comma disables bin-packing.
- /// \code
- /// TSC_Wrapped:
- /// const someArray = [
- /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
- /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
- /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
- /// // ^ inserted
- /// ]
- /// \endcode
- /// \version 11
- TrailingCommaStyle InsertTrailingCommas;
-
- /// Separator format of integer literals of different bases.
- ///
- /// If negative, remove separators. If ``0``, leave the literal as is. If
- /// positive, insert separators between digits starting from the rightmost
- /// digit.
- ///
- /// For example, the config below will leave separators in binary literals
- /// alone, insert separators in decimal literals to separate the digits into
- /// groups of 3, and remove separators in hexadecimal literals.
- /// \code
- /// IntegerLiteralSeparator:
- /// Binary: 0
- /// Decimal: 3
- /// Hex: -1
- /// \endcode
- ///
- /// You can also specify a minimum number of digits
- /// (``BinaryMinDigitsInsert``, ``DecimalMinDigitsInsert``, and
- /// ``HexMinDigitsInsert``) the integer literal must have in order for the
- /// separators to be inserted, and a maximum number of digits
- /// (``BinaryMaxDigitsRemove``, ``DecimalMaxDigitsRemove``, and
- /// ``HexMaxDigitsRemove``) until the separators are removed. This divides the
- /// literals in 3 regions, always without separator (up until including
- /// ``xxxMaxDigitsRemove``), maybe with, or without separators (up until
- /// excluding ``xxxMinDigitsInsert``), and finally always with separators.
- /// \note
- /// ``BinaryMinDigits``, ``DecimalMinDigits``, and ``HexMinDigits`` are
- /// deprecated and renamed to ``BinaryMinDigitsInsert``,
- /// ``DecimalMinDigitsInsert``, and ``HexMinDigitsInsert``, respectively.
- /// \endnote
- struct IntegerLiteralSeparatorStyle {
- /// Format separators in binary literals.
- /// \code{.text}
- /// /* -1: */ b = 0b100111101101;
- /// /* 0: */ b = 0b10011'11'0110'1;
- /// /* 3: */ b = 0b100'111'101'101;
- /// /* 4: */ b = 0b1001'1110'1101;
- /// \endcode
- int8_t Binary;
- /// Format separators in binary literals with a minimum number of digits.
- /// \code{.text}
- /// // Binary: 3
- /// // BinaryMinDigitsInsert: 7
- /// b1 = 0b101101;
- /// b2 = 0b1'101'101;
- /// \endcode
- int8_t BinaryMinDigitsInsert;
- /// Remove separators in binary literals with a maximum number of digits.
- /// \code{.text}
- /// // Binary: 3
- /// // BinaryMinDigitsInsert: 7
- /// // BinaryMaxDigitsRemove: 4
- /// b0 = 0b1011; // Always removed.
- /// b1 = 0b101101; // Not added.
- /// b2 = 0b1'01'101; // Not removed, not corrected.
- /// b3 = 0b1'101'101; // Always added.
- /// b4 = 0b10'1101; // Corrected to 0b101'101.
- /// \endcode
- int8_t BinaryMaxDigitsRemove;
- /// Format separators in decimal literals.
- /// \code{.text}
- /// /* -1: */ d = 18446744073709550592ull;
- /// /* 0: */ d = 184467'440737'0'95505'92ull;
- /// /* 3: */ d = 18'446'744'073'709'550'592ull;
- /// \endcode
- int8_t Decimal;
- /// Format separators in decimal literals with a minimum number of digits.
- /// \code{.text}
- /// // Decimal: 3
- /// // DecimalMinDigitsInsert: 5
- /// d1 = 2023;
- /// d2 = 10'000;
- /// \endcode
- int8_t DecimalMinDigitsInsert;
- /// Remove separators in decimal literals with a maximum number of digits.
- /// \code{.text}
- /// // Decimal: 3
- /// // DecimalMinDigitsInsert: 7
- /// // DecimalMaxDigitsRemove: 4
- /// d0 = 2023; // Always removed.
- /// d1 = 123456; // Not added.
- /// d2 = 1'23'456; // Not removed, not corrected.
- /// d3 = 5'000'000; // Always added.
- /// d4 = 1'23'45; // Corrected to 12'345.
- /// \endcode
- int8_t DecimalMaxDigitsRemove;
- /// Format separators in hexadecimal literals.
- /// \code{.text}
- /// /* -1: */ h = 0xDEADBEEFDEADBEEFuz;
- /// /* 0: */ h = 0xDEAD'BEEF'DE'AD'BEE'Fuz;
- /// /* 2: */ h = 0xDE'AD'BE'EF'DE'AD'BE'EFuz;
- /// \endcode
- int8_t Hex;
- /// Format separators in hexadecimal literals with a minimum number of
- /// digits.
- /// \code{.text}
- /// // Hex: 2
- /// // HexMinDigitsInsert: 6
- /// h1 = 0xABCDE;
- /// h2 = 0xAB'CD'EF;
- /// \endcode
- int8_t HexMinDigitsInsert;
- /// Remove separators in hexadecimal literals with a maximum number of
- /// digits.
- /// \code{.text}
- /// // Hex: 2
- /// // HexMinDigitsInsert: 6
- /// // HexMaxDigitsRemove: 4
- /// h0 = 0xAFFE; // Always removed.
- /// h1 = 0xABCDE; // Not added.
- /// h2 = 0xABC'DE; // Not removed, not corrected.
- /// h3 = 0xAB'CD'EF; // Always added.
- /// h4 = 0xABCD'E; // Corrected to 0xA'BC'DE.
- /// \endcode
- int8_t HexMaxDigitsRemove;
- bool operator==(const IntegerLiteralSeparatorStyle &R) const {
- return Binary == R.Binary &&
- BinaryMinDigitsInsert == R.BinaryMinDigitsInsert &&
- BinaryMaxDigitsRemove == R.BinaryMaxDigitsRemove &&
- Decimal == R.Decimal &&
- DecimalMinDigitsInsert == R.DecimalMinDigitsInsert &&
- DecimalMaxDigitsRemove == R.DecimalMaxDigitsRemove &&
- Hex == R.Hex && HexMinDigitsInsert == R.HexMinDigitsInsert &&
- HexMaxDigitsRemove == R.HexMaxDigitsRemove;
- }
- bool operator!=(const IntegerLiteralSeparatorStyle &R) const {
- return !operator==(R);
- }
- };
-
- /// Format integer literal separators (``'`` for C/C++ and ``_`` for C#, Java,
- /// and JavaScript).
- /// \version 16
- IntegerLiteralSeparatorStyle IntegerLiteralSeparator;
-
- /// A vector of prefixes ordered by the desired groups for Java imports.
- ///
- /// One group's prefix can be a subset of another - the longest prefix is
- /// always matched. Within a group, the imports are ordered lexicographically.
- /// Static imports are grouped separately and follow the same group rules.
- /// By default, static imports are placed before non-static imports,
- /// but this behavior is changed by another option,
- /// ``SortJavaStaticImport``.
- ///
- /// In the .clang-format configuration file, this can be configured like
- /// in the following yaml example. This will result in imports being
- /// formatted as in the Java example below.
- /// \code{.yaml}
- /// JavaImportGroups: [com.example, com, org]
- /// \endcode
- ///
- /// \code{.java}
- /// import static com.example.function1;
- ///
- /// import static com.test.function2;
- ///
- /// import static org.example.function3;
- ///
- /// import com.example.ClassA;
- /// import com.example.Test;
- /// import com.example.a.ClassB;
- ///
- /// import com.test.ClassC;
- ///
- /// import org.example.ClassD;
- /// \endcode
- /// \version 8
- std::vector<std::string> JavaImportGroups;
-
- /// Quotation styles for JavaScript strings. Does not affect template
- /// strings.
- enum JavaScriptQuoteStyle : int8_t {
- /// Leave string quotes as they are.
- /// \code{.js}
- /// string1 = "foo";
- /// string2 = 'bar';
- /// \endcode
- JSQS_Leave,
- /// Always use single quotes.
- /// \code{.js}
- /// string1 = 'foo';
- /// string2 = 'bar';
- /// \endcode
- JSQS_Single,
- /// Always use double quotes.
- /// \code{.js}
- /// string1 = "foo";
- /// string2 = "bar";
- /// \endcode
- JSQS_Double
- };
-
- /// The JavaScriptQuoteStyle to use for JavaScript strings.
- /// \version 3.9
- JavaScriptQuoteStyle JavaScriptQuotes;
-
- // clang-format off
- /// Whether to wrap JavaScript import/export statements.
- /// \code{.js}
- /// true:
- /// import {
- /// VeryLongImportsAreAnnoying,
- /// VeryLongImportsAreAnnoying,
- /// VeryLongImportsAreAnnoying,
- /// } from "some/module.js"
- ///
- /// false:
- /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
- /// \endcode
- /// \version 3.9
- bool JavaScriptWrapImports;
- // clang-format on
-
- /// Options regarding which empty lines are kept.
- ///
- /// For example, the config below will remove empty lines at start of the
- /// file, end of the file, and start of blocks.
- ///
- /// \code
- /// KeepEmptyLines:
- /// AtEndOfFile: false
- /// AtStartOfBlock: false
- /// AtStartOfFile: false
- /// \endcode
- struct KeepEmptyLinesStyle {
- /// Keep empty lines at end of file.
- bool AtEndOfFile;
- /// Keep empty lines at start of a block.
- /// \code
- /// true: false:
- /// if (foo) { vs. if (foo) {
- /// bar();
- /// bar(); }
- /// }
- /// \endcode
- bool AtStartOfBlock;
- /// Keep empty lines at start of file.
- bool AtStartOfFile;
- bool operator==(const KeepEmptyLinesStyle &R) const {
- return AtEndOfFile == R.AtEndOfFile &&
- AtStartOfBlock == R.AtStartOfBlock &&
- AtStartOfFile == R.AtStartOfFile;
- }
- };
- /// Which empty lines are kept. See ``MaxEmptyLinesToKeep`` for how many
- /// consecutive empty lines are kept.
- /// \version 19
- KeepEmptyLinesStyle KeepEmptyLines;
-
- /// This option is **deprecated**. See ``AtEndOfFile`` of ``KeepEmptyLines``.
- /// \version 17
- // bool KeepEmptyLinesAtEOF;
-
- /// This option is **deprecated**. See ``AtStartOfBlock`` of
- /// ``KeepEmptyLines``.
- /// \version 3.7
- // bool KeepEmptyLinesAtTheStartOfBlocks;
-
- /// Keep the form feed character if it's immediately preceded and followed by
- /// a newline. Multiple form feeds and newlines within a whitespace range are
- /// replaced with a single newline and form feed followed by the remaining
- /// newlines. (See
- /// www.gnu.org/prep/standards/html_node/Formatting.html#:~:text=formfeed.)
- /// \version 20
- bool KeepFormFeed;
-
- /// Indentation logic for lambda bodies.
- enum LambdaBodyIndentationKind : int8_t {
- /// Align lambda body relative to the lambda signature. This is the default.
- /// \code
- /// someMethod(
- /// [](SomeReallyLongLambdaSignatureArgument foo) {
- /// return;
- /// });
- /// \endcode
- LBI_Signature,
- /// For statements within block scope, align lambda body relative to the
- /// indentation level of the outer scope the lambda signature resides in.
- /// \code
- /// someMethod(
- /// [](SomeReallyLongLambdaSignatureArgument foo) {
- /// return;
- /// });
- ///
- /// someMethod(someOtherMethod(
- /// [](SomeReallyLongLambdaSignatureArgument foo) {
- /// return;
- /// }));
- /// \endcode
- LBI_OuterScope,
- };
-
- /// The indentation style of lambda bodies. ``Signature`` (the default)
- /// causes the lambda body to be indented one additional level relative to
- /// the indentation level of the signature. ``OuterScope`` forces the lambda
- /// body to be indented one additional level relative to the parent scope
- /// containing the lambda signature.
- /// \version 13
- LambdaBodyIndentationKind LambdaBodyIndentation;
-
- /// Supported languages.
- ///
- /// When stored in a configuration file, specifies the language, that the
- /// configuration targets. When passed to the ``reformat()`` function, enables
- /// syntax features specific to the language.
- enum LanguageKind : int8_t {
- /// Do not use.
- LK_None,
- /// Should be used for C.
- LK_C,
- /// Should be used for C++.
- LK_Cpp,
- /// Should be used for C#.
- LK_CSharp,
- /// Should be used for Java.
- LK_Java,
- /// Should be used for JavaScript.
- LK_JavaScript,
- /// Should be used for JSON.
- LK_Json,
- /// Should be used for Objective-C, Objective-C++.
- LK_ObjC,
- /// Should be used for Protocol Buffers
- /// (https://developers.google.com/protocol-buffers/).
- LK_Proto,
- /// Should be used for TableGen code.
- LK_TableGen,
- /// Should be used for Protocol Buffer messages in text format
- /// (https://developers.google.com/protocol-buffers/).
- LK_TextProto,
- /// Should be used for Verilog and SystemVerilog.
- /// https://standards.ieee.org/ieee/1800/6700/
- /// https://sci-hub.st/10.1109/IEEESTD.2018.8299595
- LK_Verilog
- };
- bool isCpp() const {
- return Language == LK_Cpp || Language == LK_C || Language == LK_ObjC;
- }
- bool isCSharp() const { return Language == LK_CSharp; }
- bool isJson() const { return Language == LK_Json; }
- bool isJava() const { return Language == LK_Java; }
- bool isJavaScript() const { return Language == LK_JavaScript; }
- bool isVerilog() const { return Language == LK_Verilog; }
- bool isTextProto() const { return Language == LK_TextProto; }
- bool isProto() const { return Language == LK_Proto || isTextProto(); }
- bool isTableGen() const { return Language == LK_TableGen; }
-
- /// The language that this format style targets.
- /// \note
- /// You can specify the language (``C``, ``Cpp``, or ``ObjC``) for ``.h``
- /// files by adding a ``// clang-format Language:`` line before the first
- /// non-comment (and non-empty) line, e.g. ``// clang-format Language: Cpp``.
- /// \endnote
- /// \version 3.5
- LanguageKind Language;
-
- /// Line ending style.
- enum LineEndingStyle : int8_t {
- /// Use ``\n``.
- LE_LF,
- /// Use ``\r\n``.
- LE_CRLF,
- /// Use ``\n`` unless the input has more lines ending in ``\r\n``.
- LE_DeriveLF,
- /// Use ``\r\n`` unless the input has more lines ending in ``\n``.
- LE_DeriveCRLF,
- };
-
- /// Line ending style (``\n`` or ``\r\n``) to use.
- /// \version 16
- LineEndingStyle LineEnding;
-
- /// A regular expression matching macros that start a block.
- /// \code
- /// # With:
- /// MacroBlockBegin: "^NS_MAP_BEGIN|\
- /// NS_TABLE_HEAD$"
- /// MacroBlockEnd: "^\
- /// NS_MAP_END|\
- /// NS_TABLE_.*_END$"
- ///
- /// NS_MAP_BEGIN
- /// foo();
- /// NS_MAP_END
- ///
- /// NS_TABLE_HEAD
- /// bar();
- /// NS_TABLE_FOO_END
- ///
- /// # Without:
- /// NS_MAP_BEGIN
- /// foo();
- /// NS_MAP_END
- ///
- /// NS_TABLE_HEAD
- /// bar();
- /// NS_TABLE_FOO_END
- /// \endcode
- /// \version 3.7
- std::string MacroBlockBegin;
-
- /// A regular expression matching macros that end a block.
- /// \version 3.7
- std::string MacroBlockEnd;
-
- /// A list of macros of the form \c <definition>=<expansion> .
- ///
- /// Code will be parsed with macros expanded, in order to determine how to
- /// interpret and format the macro arguments.
- ///
- /// For example, the code:
- /// \code
- /// A(a*b);
- /// \endcode
- ///
- /// will usually be interpreted as a call to a function A, and the
- /// multiplication expression will be formatted as ``a * b``.
- ///
- /// If we specify the macro definition:
- /// \code{.yaml}
- /// Macros:
- /// - A(x)=x
- /// \endcode
- ///
- /// the code will now be parsed as a declaration of the variable b of type a*,
- /// and formatted as ``a* b`` (depending on pointer-binding rules).
- ///
- /// Features and restrictions:
- /// * Both function-like macros and object-like macros are supported.
- /// * Macro arguments must be used exactly once in the expansion.
- /// * No recursive expansion; macros referencing other macros will be
- /// ignored.
- /// * Overloading by arity is supported: for example, given the macro
- /// definitions A=x, A()=y, A(a)=a
- ///
- /// \code
- /// A; -> x;
- /// A(); -> y;
- /// A(z); -> z;
- /// A(a, b); // will not be expanded.
- /// \endcode
- ///
- /// \version 17
- std::vector<std::string> Macros;
-
- /// A vector of function-like macros whose invocations should be skipped by
- /// ``RemoveParentheses``.
- /// \version 21
- std::vector<std::string> MacrosSkippedByRemoveParentheses;
-
- /// The maximum number of consecutive empty lines to keep.
- /// \code
- /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
- /// int f() { int f() {
- /// int = 1; int i = 1;
- /// i = foo();
- /// i = foo(); return i;
- /// }
- /// return i;
- /// }
- /// \endcode
- /// \version 3.7
- unsigned MaxEmptyLinesToKeep;
-
- /// Different ways to indent namespace contents.
- enum NamespaceIndentationKind : int8_t {
- /// Don't indent in namespaces.
- /// \code
- /// namespace out {
- /// int i;
- /// namespace in {
- /// int i;
- /// }
- /// }
- /// \endcode
- NI_None,
- /// Indent only in inner namespaces (nested in other namespaces).
- /// \code
- /// namespace out {
- /// int i;
- /// namespace in {
- /// int i;
- /// }
- /// }
- /// \endcode
- NI_Inner,
- /// Indent in all namespaces.
- /// \code
- /// namespace out {
- /// int i;
- /// namespace in {
- /// int i;
- /// }
- /// }
- /// \endcode
- NI_All
- };
-
- /// The indentation used for namespaces.
- /// \version 3.7
- NamespaceIndentationKind NamespaceIndentation;
-
- /// A vector of macros which are used to open namespace blocks.
- ///
- /// These are expected to be macros of the form:
- /// \code
- /// NAMESPACE(<namespace-name>, ...) {
- /// <namespace-content>
- /// }
- /// \endcode
- ///
- /// For example: TESTSUITE
- /// \version 9
- std::vector<std::string> NamespaceMacros;
-
- /// Control over each component in a numeric literal.
- enum NumericLiteralComponentStyle : int8_t {
- /// Leave this component of the literal as is.
- NLCS_Leave,
- /// Format this component with uppercase characters.
- NLCS_Upper,
- /// Format this component with lowercase characters.
- NLCS_Lower,
- };
-
- /// Separate control for each numeric literal component.
- ///
- /// For example, the config below will leave exponent letters alone, reformat
- /// hexadecimal digits in lowercase, reformat numeric literal prefixes in
- /// uppercase, and reformat suffixes in lowercase.
- /// \code
- /// NumericLiteralCase:
- /// ExponentLetter: Leave
- /// HexDigit: Lower
- /// Prefix: Upper
- /// Suffix: Lower
- /// \endcode
- struct NumericLiteralCaseStyle {
- /// Format floating point exponent separator letter case.
- /// \code
- /// float a = 6.02e23 + 1.0E10; // Leave
- /// float a = 6.02E23 + 1.0E10; // Upper
- /// float a = 6.02e23 + 1.0e10; // Lower
- /// \endcode
- NumericLiteralComponentStyle ExponentLetter;
- /// Format hexadecimal digit case.
- /// \code
- /// a = 0xaBcDeF; // Leave
- /// a = 0xABCDEF; // Upper
- /// a = 0xabcdef; // Lower
- /// \endcode
- NumericLiteralComponentStyle HexDigit;
- /// Format integer prefix case.
- /// \code
- /// a = 0XF0 | 0b1; // Leave
- /// a = 0XF0 | 0B1; // Upper
- /// a = 0xF0 | 0b1; // Lower
- /// \endcode
- NumericLiteralComponentStyle Prefix;
- /// Format suffix case. This option excludes case-sensitive reserved
- /// suffixes, such as ``min`` in C++.
- /// \code
- /// a = 1uLL; // Leave
- /// a = 1ULL; // Upper
- /// a = 1ull; // Lower
- /// \endcode
- NumericLiteralComponentStyle Suffix;
-
- bool operator==(const NumericLiteralCaseStyle &R) const {
- return ExponentLetter == R.ExponentLetter && HexDigit == R.HexDigit &&
- Prefix == R.Prefix && Suffix == R.Suffix;
- }
-
- bool operator!=(const NumericLiteralCaseStyle &R) const {
- return !(*this == R);
- }
- };
-
- /// Capitalization style for numeric literals.
- /// \version 22
- NumericLiteralCaseStyle NumericLiteralCase;
-
- /// Controls bin-packing Objective-C protocol conformance list
- /// items into as few lines as possible when they go over ``ColumnLimit``.
- ///
- /// If ``Auto`` (the default), delegates to the value in
- /// ``BinPackParameters``. If that is ``BinPack``, bin-packs Objective-C
- /// protocol conformance list items into as few lines as possible
- /// whenever they go over ``ColumnLimit``.
- ///
- /// If ``Always``, always bin-packs Objective-C protocol conformance
- /// list items into as few lines as possible whenever they go over
- /// ``ColumnLimit``.
- ///
- /// If ``Never``, lays out Objective-C protocol conformance list items
- /// onto individual lines whenever they go over ``ColumnLimit``.
- ///
- /// \code{.objc}
- /// Always (or Auto, if BinPackParameters==BinPack):
- /// @interface ccccccccccccc () <
- /// ccccccccccccc, ccccccccccccc,
- /// ccccccccccccc, ccccccccccccc> {
- /// }
- ///
- /// Never (or Auto, if BinPackParameters!=BinPack):
- /// @interface ddddddddddddd () <
- /// ddddddddddddd,
- /// ddddddddddddd,
- /// ddddddddddddd,
- /// ddddddddddddd> {
- /// }
- /// \endcode
- /// \version 7
- BinPackStyle ObjCBinPackProtocolList;
-
- /// The number of characters to use for indentation of ObjC blocks.
- /// \code{.objc}
- /// ObjCBlockIndentWidth: 4
- ///
- /// [operation setCompletionBlock:^{
- /// [self onOperationDone];
- /// }];
- /// \endcode
- /// \version 3.7
- unsigned ObjCBlockIndentWidth;
-
- /// Break parameters list into lines when there is nested block
- /// parameters in a function call.
- /// \code
- /// false:
- /// - (void)_aMethod
- /// {
- /// [self.test1 t:self w:self callback:^(typeof(self) self, NSNumber
- /// *u, NSNumber *v) {
- /// u = c;
- /// }]
- /// }
- /// true:
- /// - (void)_aMethod
- /// {
- /// [self.test1 t:self
- /// w:self
- /// callback:^(typeof(self) self, NSNumber *u, NSNumber *v) {
- /// u = c;
- /// }]
- /// }
- /// \endcode
- /// \version 11
- bool ObjCBreakBeforeNestedBlockParam;
-
- /// The order in which ObjC property attributes should appear.
- ///
- /// Attributes in code will be sorted in the order specified. Any attributes
- /// encountered that are not mentioned in this array will be sorted last, in
- /// stable order. Comments between attributes will leave the attributes
- /// untouched.
- /// \warning
- /// Using this option could lead to incorrect code formatting due to
- /// clang-format's lack of complete semantic information. As such, extra
- /// care should be taken to review code changes made by this option.
- /// \endwarning
- /// \code{.yaml}
- /// ObjCPropertyAttributeOrder: [
- /// class, direct,
- /// atomic, nonatomic,
- /// assign, retain, strong, copy, weak, unsafe_unretained,
- /// readonly, readwrite, getter, setter,
- /// nullable, nonnull, null_resettable, null_unspecified
- /// ]
- /// \endcode
- /// \version 18
- std::vector<std::string> ObjCPropertyAttributeOrder;
-
- /// Add or remove a space between the '-'/'+' and the return type in
- /// Objective-C method declarations. i.e
- /// \code{.objc}
- /// false: true:
- ///
- /// -(void)method vs. - (void)method
- /// \endcode
- /// \version 23
- bool ObjCSpaceAfterMethodDeclarationPrefix;
-
- /// Add a space after ``@property`` in Objective-C, i.e. use
- /// ``@property (readonly)`` instead of ``@property(readonly)``.
- /// \version 3.7
- bool ObjCSpaceAfterProperty;
-
- /// Add a space in front of an Objective-C protocol list, i.e. use
- /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
- /// \version 3.7
- bool ObjCSpaceBeforeProtocolList;
-
- /// A regular expression that describes markers for turning formatting off for
- /// one line. If it matches a comment that is the only token of a line,
- /// clang-format skips the comment and the next line. Otherwise, clang-format
- /// skips lines containing a matched token.
- /// \note
- /// This option does not apply to ``IntegerLiteralSeparator`` and
- /// ``NumericLiteralCase``.
- /// \endnote
- /// \code
- /// // OneLineFormatOffRegex: ^(// NOLINT|logger$)
- /// // results in the output below:
- /// int a;
- /// int b ; // NOLINT
- /// int c;
- /// // NOLINTNEXTLINE
- /// int d ;
- /// int e;
- /// s = "// NOLINT";
- /// logger() ;
- /// logger2();
- /// my_logger();
- /// \endcode
- /// \version 21
- std::string OneLineFormatOffRegex;
-
- /// Different ways to try to fit all constructor initializers on a line.
- enum PackConstructorInitializersStyle : int8_t {
- /// Always put each constructor initializer on its own line.
- /// \code
- /// Constructor()
- /// : a(),
- /// b()
- /// \endcode
- PCIS_Never,
- /// Bin-pack constructor initializers.
- /// \code
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(),
- /// cccccccccccccccccccc()
- /// \endcode
- PCIS_BinPack,
- /// Put all constructor initializers on the current line if they fit.
- /// Otherwise, put each one on its own line.
- /// \code
- /// Constructor() : a(), b()
- ///
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(),
- /// bbbbbbbbbbbbbbbbbbbb(),
- /// ddddddddddddd()
- /// \endcode
- PCIS_CurrentLine,
- /// Same as ``PCIS_CurrentLine`` except that if all constructor initializers
- /// do not fit on the current line, try to fit them on the next line.
- /// \code
- /// Constructor() : a(), b()
- ///
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()
- ///
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(),
- /// bbbbbbbbbbbbbbbbbbbb(),
- /// cccccccccccccccccccc()
- /// \endcode
- PCIS_NextLine,
- /// Put all constructor initializers on the next line if they fit.
- /// Otherwise, put each one on its own line.
- /// \code
- /// Constructor()
- /// : a(), b()
- ///
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()
- ///
- /// Constructor()
- /// : aaaaaaaaaaaaaaaaaaaa(),
- /// bbbbbbbbbbbbbbbbbbbb(),
- /// cccccccccccccccccccc()
- /// \endcode
- PCIS_NextLineOnly,
- };
-
- /// The pack constructor initializers style to use.
- /// \version 14
- PackConstructorInitializersStyle PackConstructorInitializers;
-
- /// The penalty for breaking around an assignment operator.
- /// \version 5
- unsigned PenaltyBreakAssignment;
-
- /// The penalty for breaking a function call after ``call(``.
- /// \version 3.7
- unsigned PenaltyBreakBeforeFirstCallParameter;
-
- /// The penalty for breaking before a member access operator (``.``, ``->``).
- /// \version 20
- unsigned PenaltyBreakBeforeMemberAccess;
-
- /// The penalty for each line break introduced inside a comment.
- /// \version 3.7
- unsigned PenaltyBreakComment;
-
- /// The penalty for breaking before the first ``<<``.
- /// \version 3.7
- unsigned PenaltyBreakFirstLessLess;
-
- /// The penalty for breaking after ``(``.
- /// \version 14
- unsigned PenaltyBreakOpenParenthesis;
-
- /// The penalty for breaking after ``::``.
- /// \version 18
- unsigned PenaltyBreakScopeResolution;
-
- /// The penalty for each line break introduced inside a string literal.
- /// \version 3.7
- unsigned PenaltyBreakString;
-
- /// The penalty for breaking after template declaration.
- /// \version 7
- unsigned PenaltyBreakTemplateDeclaration;
-
- /// The penalty for each character outside of the column limit.
- /// \version 3.7
- unsigned PenaltyExcessCharacter;
-
- /// Penalty for each character of whitespace indentation
- /// (counted relative to leading non-whitespace column).
- /// \version 12
- unsigned PenaltyIndentedWhitespace;
-
- /// Penalty for putting the return type of a function onto its own line.
- /// \version 3.7
- unsigned PenaltyReturnTypeOnItsOwnLine;
-
- /// The ``&``, ``&&`` and ``*`` alignment style.
- enum PointerAlignmentStyle : int8_t {
- /// Align pointer to the left.
- /// \code
- /// int* a;
- /// \endcode
- PAS_Left,
- /// Align pointer to the right.
- /// \code
- /// int *a;
- /// \endcode
- PAS_Right,
- /// Align pointer in the middle.
- /// \code
- /// int * a;
- /// \endcode
- PAS_Middle
- };
-
- /// Pointer and reference alignment style.
- /// \version 3.7
- PointerAlignmentStyle PointerAlignment;
-
- /// The number of columns to use for indentation of preprocessor statements.
- /// When set to -1 (default) ``IndentWidth`` is used also for preprocessor
- /// statements.
- /// \code
- /// PPIndentWidth: 1
- ///
- /// #ifdef __linux__
- /// # define FOO
- /// #else
- /// # define BAR
- /// #endif
- /// \endcode
- /// \version 13
- int PPIndentWidth;
-
- /// Different specifiers and qualifiers alignment styles.
- enum QualifierAlignmentStyle : int8_t {
- /// Don't change specifiers/qualifiers to either Left or Right alignment
- /// (default).
- /// \code
- /// int const a;
- /// const int *a;
- /// \endcode
- QAS_Leave,
- /// Change specifiers/qualifiers to be left-aligned.
- /// \code
- /// const int a;
- /// const int *a;
- /// \endcode
- QAS_Left,
- /// Change specifiers/qualifiers to be right-aligned.
- /// \code
- /// int const a;
- /// int const *a;
- /// \endcode
- QAS_Right,
- /// Change specifiers/qualifiers to be aligned based on ``QualifierOrder``.
- /// With:
- /// \code{.yaml}
- /// QualifierOrder: [inline, static, type, const]
- /// \endcode
- ///
- /// \code
- ///
- /// int const a;
- /// int const *a;
- /// \endcode
- QAS_Custom
- };
-
- /// Different ways to arrange specifiers and qualifiers (e.g. const/volatile).
- /// \warning
- /// Setting ``QualifierAlignment`` to something other than ``Leave``, COULD
- /// lead to incorrect code formatting due to incorrect decisions made due to
- /// clang-formats lack of complete semantic information.
- /// As such extra care should be taken to review code changes made by the use
- /// of this option.
- /// \endwarning
- /// \version 14
- QualifierAlignmentStyle QualifierAlignment;
-
- /// The order in which the qualifiers appear.
- /// The order is an array that can contain any of the following:
- ///
- /// * ``const``
- /// * ``inline``
- /// * ``static``
- /// * ``friend``
- /// * ``constexpr``
- /// * ``volatile``
- /// * ``restrict``
- /// * ``type``
- ///
- /// \note
- /// It must contain ``type``.
- /// \endnote
- ///
- /// Items to the left of ``type`` will be placed to the left of the type and
- /// aligned in the order supplied. Items to the right of ``type`` will be
- /// placed to the right of the type and aligned in the order supplied.
- ///
- /// \code{.yaml}
- /// QualifierOrder: [inline, static, type, const, volatile]
- /// \endcode
- /// \version 14
- std::vector<std::string> QualifierOrder;
-
- /// See documentation of ``RawStringFormats``.
- struct RawStringFormat {
- /// The language of this raw string.
- LanguageKind Language;
- /// A list of raw string delimiters that match this language.
- std::vector<std::string> Delimiters;
- /// A list of enclosing function names that match this language.
- std::vector<std::string> EnclosingFunctions;
- /// The canonical delimiter for this language.
- std::string CanonicalDelimiter;
- /// The style name on which this raw string format is based on.
- /// If not specified, the raw string format is based on the style that this
- /// format is based on.
- std::string BasedOnStyle;
- bool operator==(const RawStringFormat &Other) const {
- return Language == Other.Language && Delimiters == Other.Delimiters &&
- EnclosingFunctions == Other.EnclosingFunctions &&
- CanonicalDelimiter == Other.CanonicalDelimiter &&
- BasedOnStyle == Other.BasedOnStyle;
- }
- };
-
- /// Defines hints for detecting supported languages code blocks in raw
- /// strings.
- ///
- /// A raw string with a matching delimiter or a matching enclosing function
- /// name will be reformatted assuming the specified language based on the
- /// style for that language defined in the .clang-format file. If no style has
- /// been defined in the .clang-format file for the specific language, a
- /// predefined style given by ``BasedOnStyle`` is used. If ``BasedOnStyle`` is
- /// not found, the formatting is based on ``LLVM`` style. A matching delimiter
- /// takes precedence over a matching enclosing function name for determining
- /// the language of the raw string contents.
- ///
- /// If a canonical delimiter is specified, occurrences of other delimiters for
- /// the same language will be updated to the canonical if possible.
- ///
- /// There should be at most one specification per language and each delimiter
- /// and enclosing function should not occur in multiple specifications.
- ///
- /// To configure this in the .clang-format file, use:
- /// \code{.yaml}
- /// RawStringFormats:
- /// - Language: TextProto
- /// Delimiters:
- /// - pb
- /// - proto
- /// EnclosingFunctions:
- /// - PARSE_TEXT_PROTO
- /// BasedOnStyle: google
- /// - Language: Cpp
- /// Delimiters:
- /// - cc
- /// - cpp
- /// BasedOnStyle: LLVM
- /// CanonicalDelimiter: cc
- /// \endcode
- /// \version 6
- std::vector<RawStringFormat> RawStringFormats;
-
- /// The ``&`` and ``&&`` alignment style.
- enum ReferenceAlignmentStyle : int8_t {
- /// Align reference like ``PointerAlignment``.
- RAS_Pointer,
- /// Align reference to the left.
- /// \code
- /// int& a;
- /// \endcode
- RAS_Left,
- /// Align reference to the right.
- /// \code
- /// int &a;
- /// \endcode
- RAS_Right,
- /// Align reference in the middle.
- /// \code
- /// int & a;
- /// \endcode
- RAS_Middle
- };
-
- /// Reference alignment style (overrides ``PointerAlignment`` for references).
- /// \version 13
- ReferenceAlignmentStyle ReferenceAlignment;
-
- // clang-format off
- /// Types of comment reflow style.
- enum ReflowCommentsStyle : int8_t {
- /// Leave comments untouched.
- /// \code
- /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
- /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
- /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
- /// * and a misaligned second line */
- /// \endcode
- RCS_Never,
- /// Only apply indentation rules, moving comments left or right, without
- /// changing formatting inside the comments.
- /// \code
- /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
- /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
- /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
- /// * and a misaligned second line */
- /// \endcode
- RCS_IndentOnly,
- /// Apply indentation rules and reflow long comments into new lines, trying
- /// to obey the ``ColumnLimit``.
- /// \code
- /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
- /// // information
- /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
- /// * information */
- /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
- /// * information and a misaligned second line */
- /// \endcode
- RCS_Always
- };
- // clang-format on
-
- /// Comment reformatting style.
- /// \version 3.8
- ReflowCommentsStyle ReflowComments;
-
- /// Remove optional braces of control statements (``if``, ``else``, ``for``,
- /// and ``while``) in C++ according to the LLVM coding style.
- /// \warning
- /// This option will be renamed and expanded to support other styles.
- /// \endwarning
- /// \warning
- /// Setting this option to ``true`` could lead to incorrect code formatting
- /// due to clang-format's lack of complete semantic information. As such,
- /// extra care should be taken to review code changes made by this option.
- /// \endwarning
- /// \code
- /// false: true:
- ///
- /// if (isa<FunctionDecl>(D)) { vs. if (isa<FunctionDecl>(D))
- /// handleFunctionDecl(D); handleFunctionDecl(D);
- /// } else if (isa<VarDecl>(D)) { else if (isa<VarDecl>(D))
- /// handleVarDecl(D); handleVarDecl(D);
- /// }
- ///
- /// if (isa<VarDecl>(D)) { vs. if (isa<VarDecl>(D)) {
- /// for (auto *A : D.attrs()) { for (auto *A : D.attrs())
- /// if (shouldProcessAttr(A)) { if (shouldProcessAttr(A))
- /// handleAttr(A); handleAttr(A);
- /// } }
- /// }
- /// }
- ///
- /// if (isa<FunctionDecl>(D)) { vs. if (isa<FunctionDecl>(D))
- /// for (auto *A : D.attrs()) { for (auto *A : D.attrs())
- /// handleAttr(A); handleAttr(A);
- /// }
- /// }
- ///
- /// if (auto *D = (T)(D)) { vs. if (auto *D = (T)(D)) {
- /// if (shouldProcess(D)) { if (shouldProcess(D))
- /// handleVarDecl(D); handleVarDecl(D);
- /// } else { else
- /// markAsIgnored(D); markAsIgnored(D);
- /// } }
- /// }
- ///
- /// if (a) { vs. if (a)
- /// b(); b();
- /// } else { else if (c)
- /// if (c) { d();
- /// d(); else
- /// } else { e();
- /// e();
- /// }
- /// }
- /// \endcode
- /// \version 14
- bool RemoveBracesLLVM;
-
- /// Remove empty lines within unwrapped lines.
- /// \code
- /// false: true:
- ///
- /// int c vs. int c = a + b;
- ///
- /// = a + b;
- ///
- /// enum : unsigned vs. enum : unsigned {
- /// AA = 0,
- /// { BB
- /// AA = 0, } myEnum;
- /// BB
- /// } myEnum;
- ///
- /// while ( vs. while (true) {
- /// }
- /// true) {
- /// }
- /// \endcode
- /// \version 20
- bool RemoveEmptyLinesInUnwrappedLines;
-
- /// Types of redundant parentheses to remove.
- enum RemoveParenthesesStyle : int8_t {
- /// Do not remove parentheses.
- /// \code
- /// class __declspec((dllimport)) X {};
- /// co_return (((0)));
- /// return ((a + b) - ((c + d)));
- /// \endcode
- RPS_Leave,
- /// Replace multiple parentheses with single parentheses.
- /// \code
- /// class __declspec(dllimport) X {};
- /// co_return (0);
- /// return ((a + b) - (c + d));
- /// \endcode
- RPS_MultipleParentheses,
- /// Also remove parentheses enclosing the expression in a
- /// ``return``/``co_return`` statement.
- /// \code
- /// class __declspec(dllimport) X {};
- /// co_return 0;
- /// return (a + b) - (c + d);
- /// \endcode
- RPS_ReturnStatement,
- };
-
- /// Remove redundant parentheses.
- /// \warning
- /// Setting this option to any value other than ``Leave`` could lead to
- /// incorrect code formatting due to clang-format's lack of complete semantic
- /// information. As such, extra care should be taken to review code changes
- /// made by this option.
- /// \endwarning
- /// \version 17
- RemoveParenthesesStyle RemoveParentheses;
-
- /// Remove semicolons after the closing braces of functions and
- /// constructors/destructors.
- /// \warning
- /// Setting this option to ``true`` could lead to incorrect code formatting
- /// due to clang-format's lack of complete semantic information. As such,
- /// extra care should be taken to review code changes made by this option.
- /// \endwarning
- /// \code
- /// false: true:
- ///
- /// int max(int a, int b) { int max(int a, int b) {
- /// return a > b ? a : b; return a > b ? a : b;
- /// }; }
- ///
- /// \endcode
- /// \version 16
- bool RemoveSemicolon;
-
- /// The possible positions for the requires clause. The ``IndentRequires``
- /// option is only used if the ``requires`` is put on the start of a line.
- enum RequiresClausePositionStyle : int8_t {
- /// Always put the ``requires`` clause on its own line (possibly followed by
- /// a semicolon).
- /// \code
- /// template <typename T>
- /// requires C<T>
- /// struct Foo {...
- ///
- /// template <typename T>
- /// void bar(T t)
- /// requires C<T>;
- ///
- /// template <typename T>
- /// requires C<T>
- /// void bar(T t) {...
- ///
- /// template <typename T>
- /// void baz(T t)
- /// requires C<T>
- /// {...
- /// \endcode
- RCPS_OwnLine,
- /// As with ``OwnLine``, except, unless otherwise prohibited, place a
- /// following open brace (of a function definition) to follow on the same
- /// line.
- /// \code
- /// void bar(T t)
- /// requires C<T> {
- /// return;
- /// }
- ///
- /// void bar(T t)
- /// requires C<T> {}
- ///
- /// template <typename T>
- /// requires C<T>
- /// void baz(T t) {
- /// ...
- /// \endcode
- RCPS_OwnLineWithBrace,
- /// Try to put the clause together with the preceding part of a declaration.
- /// For class templates: stick to the template declaration.
- /// For function templates: stick to the template declaration.
- /// For function declaration followed by a requires clause: stick to the
- /// parameter list.
- /// \code
- /// template <typename T> requires C<T>
- /// struct Foo {...
- ///
- /// template <typename T> requires C<T>
- /// void bar(T t) {...
- ///
- /// template <typename T>
- /// void baz(T t) requires C<T>
- /// {...
- /// \endcode
- RCPS_WithPreceding,
- /// Try to put the ``requires`` clause together with the class or function
- /// declaration.
- /// \code
- /// template <typename T>
- /// requires C<T> struct Foo {...
- ///
- /// template <typename T>
- /// requires C<T> void bar(T t) {...
- ///
- /// template <typename T>
- /// void baz(T t)
- /// requires C<T> {...
- /// \endcode
- RCPS_WithFollowing,
- /// Try to put everything in the same line if possible. Otherwise normal
- /// line breaking rules take over.
- /// \code
- /// // Fitting:
- /// template <typename T> requires C<T> struct Foo {...
- ///
- /// template <typename T> requires C<T> void bar(T t) {...
- ///
- /// template <typename T> void bar(T t) requires C<T> {...
- ///
- /// // Not fitting, one possible example:
- /// template <typename LongName>
- /// requires C<LongName>
- /// struct Foo {...
- ///
- /// template <typename LongName>
- /// requires C<LongName>
- /// void bar(LongName ln) {
- ///
- /// template <typename LongName>
- /// void bar(LongName ln)
- /// requires C<LongName> {
- /// \endcode
- RCPS_SingleLine,
- };
-
- /// The position of the ``requires`` clause.
- /// \version 15
- RequiresClausePositionStyle RequiresClausePosition;
-
- /// Indentation logic for requires expression bodies.
- enum RequiresExpressionIndentationKind : int8_t {
- /// Align requires expression body relative to the indentation level of the
- /// outer scope the requires expression resides in.
- /// This is the default.
- /// \code
- /// template <typename T>
- /// concept C = requires(T t) {
- /// ...
- /// }
- /// \endcode
- REI_OuterScope,
- /// Align requires expression body relative to the ``requires`` keyword.
- /// \code
- /// template <typename T>
- /// concept C = requires(T t) {
- /// ...
- /// }
- /// \endcode
- REI_Keyword,
- };
-
- /// The indentation used for requires expression bodies.
- /// \version 16
- RequiresExpressionIndentationKind RequiresExpressionIndentation;
-
- /// The style if definition blocks should be separated.
- enum SeparateDefinitionStyle : int8_t {
- /// Leave definition blocks as they are.
- SDS_Leave,
- /// Insert an empty line between definition blocks.
- SDS_Always,
- /// Remove any empty line between definition blocks.
- SDS_Never
- };
-
- /// Specifies the use of empty lines to separate definition blocks, including
- /// classes, structs, enums, and functions.
- /// \code
- /// Never v.s. Always
- /// #include <cstring> #include <cstring>
- /// struct Foo {
- /// int a, b, c; struct Foo {
- /// }; int a, b, c;
- /// namespace Ns { };
- /// class Bar {
- /// public: namespace Ns {
- /// struct Foobar { class Bar {
- /// int a; public:
- /// int b; struct Foobar {
- /// }; int a;
- /// private: int b;
- /// int t; };
- /// int method1() {
- /// // ... private:
- /// } int t;
- /// enum List {
- /// ITEM1, int method1() {
- /// ITEM2 // ...
- /// }; }
- /// template<typename T>
- /// int method2(T x) { enum List {
- /// // ... ITEM1,
- /// } ITEM2
- /// int i, j, k; };
- /// int method3(int par) {
- /// // ... template<typename T>
- /// } int method2(T x) {
- /// }; // ...
- /// class C {}; }
- /// }
- /// int i, j, k;
- ///
- /// int method3(int par) {
- /// // ...
- /// }
- /// };
- ///
- /// class C {};
- /// }
- /// \endcode
- /// \version 14
- SeparateDefinitionStyle SeparateDefinitionBlocks;
-
- /// The maximal number of unwrapped lines that a short namespace spans.
- /// Defaults to 1.
- ///
- /// This determines the maximum length of short namespaces by counting
- /// unwrapped lines (i.e. containing neither opening nor closing
- /// namespace brace) and makes ``FixNamespaceComments`` omit adding
- /// end comments for those.
- /// \code
- /// ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0
- /// namespace a { namespace a {
- /// int foo; int foo;
- /// } } // namespace a
- ///
- /// ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0
- /// namespace b { namespace b {
- /// int foo; int foo;
- /// int bar; int bar;
- /// } // namespace b } // namespace b
- /// \endcode
- /// \version 13
- unsigned ShortNamespaceLines;
-
- /// Do not format macro definition body.
- /// \version 18
- bool SkipMacroDefinitionBody;
-
- /// Includes sorting options.
- struct SortIncludesOptions {
- /// If ``true``, includes are sorted based on the other suboptions below.
- /// (``Never`` is deprecated by ``Enabled: false``.)
- bool Enabled;
- /// Whether or not includes are sorted in a case-insensitive fashion.
- /// (``CaseSensitive`` and ``CaseInsensitive`` are deprecated by
- /// ``IgnoreCase: false`` and ``IgnoreCase: true``, respectively.)
- /// \code
- /// true: false:
- /// #include "A/B.h" vs. #include "A/B.h"
- /// #include "A/b.h" #include "A/b.h"
- /// #include "a/b.h" #include "B/A.h"
- /// #include "B/A.h" #include "B/a.h"
- /// #include "B/a.h" #include "a/b.h"
- /// \endcode
- bool IgnoreCase;
- /// When sorting includes in each block, only take file extensions into
- /// account if two includes compare equal otherwise.
- /// \code
- /// true: false:
- /// # include "A.h" vs. # include "A-util.h"
- /// # include "A.inc" # include "A.h"
- /// # include "A-util.h" # include "A.inc"
- /// \endcode
- bool IgnoreExtension;
- bool operator==(const SortIncludesOptions &R) const {
- return Enabled == R.Enabled && IgnoreCase == R.IgnoreCase &&
- IgnoreExtension == R.IgnoreExtension;
- }
- bool operator!=(const SortIncludesOptions &R) const {
- return !(*this == R);
- }
- };
-
- /// Controls if and how clang-format will sort ``#includes``.
- /// \version 3.8
- SortIncludesOptions SortIncludes;
-
- /// Position for Java Static imports.
- enum SortJavaStaticImportOptions : int8_t {
- /// Static imports are placed before non-static imports.
- /// \code{.java}
- /// import static org.example.function1;
- ///
- /// import org.example.ClassA;
- /// \endcode
- SJSIO_Before,
- /// Static imports are placed after non-static imports.
- /// \code{.java}
- /// import org.example.ClassA;
- ///
- /// import static org.example.function1;
- /// \endcode
- SJSIO_After,
- };
-
- /// When sorting Java imports, by default static imports are placed before
- /// non-static imports. If ``JavaStaticImportAfterImport`` is ``After``,
- /// static imports are placed after non-static imports.
- /// \version 12
- SortJavaStaticImportOptions SortJavaStaticImport;
-
- /// Using declaration sorting options.
- enum SortUsingDeclarationsOptions : int8_t {
- /// Using declarations are never sorted.
- /// \code
- /// using std::chrono::duration_cast;
- /// using std::move;
- /// using boost::regex;
- /// using boost::regex_constants::icase;
- /// using std::string;
- /// \endcode
- SUD_Never,
- /// Using declarations are sorted in the order defined as follows:
- /// Split the strings by ``::`` and discard any initial empty strings. Sort
- /// the lists of names lexicographically, and within those groups, names are
- /// in case-insensitive lexicographic order.
- /// \code
- /// using boost::regex;
- /// using boost::regex_constants::icase;
- /// using std::chrono::duration_cast;
- /// using std::move;
- /// using std::string;
- /// \endcode
- SUD_Lexicographic,
- /// Using declarations are sorted in the order defined as follows:
- /// Split the strings by ``::`` and discard any initial empty strings. The
- /// last element of each list is a non-namespace name; all others are
- /// namespace names. Sort the lists of names lexicographically, where the
- /// sort order of individual names is that all non-namespace names come
- /// before all namespace names, and within those groups, names are in
- /// case-insensitive lexicographic order.
- /// \code
- /// using boost::regex;
- /// using boost::regex_constants::icase;
- /// using std::move;
- /// using std::string;
- /// using std::chrono::duration_cast;
- /// \endcode
- SUD_LexicographicNumeric,
- };
-
- /// Controls if and how clang-format will sort using declarations.
- /// \version 5
- SortUsingDeclarationsOptions SortUsingDeclarations;
-
- /// If ``true``, a space is inserted after C style casts.
- /// \code
- /// true: false:
- /// (int) i; vs. (int)i;
- /// \endcode
- /// \version 3.5
- bool SpaceAfterCStyleCast;
-
- /// If ``true``, a space is inserted after the logical not operator (``!``).
- /// \code
- /// true: false:
- /// ! someExpression(); vs. !someExpression();
- /// \endcode
- /// \version 9
- bool SpaceAfterLogicalNot;
-
- /// If ``true``, a space will be inserted after the ``operator`` keyword.
- /// \code
- /// true: false:
- /// bool operator ==(int a); vs. bool operator==(int a);
- /// \endcode
- /// \version 21
- bool SpaceAfterOperatorKeyword;
-
- /// If \c true, a space will be inserted after the ``template`` keyword.
- /// \code
- /// true: false:
- /// template <int> void foo(); vs. template<int> void foo();
- /// \endcode
- /// \version 4
- bool SpaceAfterTemplateKeyword;
-
- /// Different ways to put a space before opening parentheses.
- enum SpaceAroundPointerQualifiersStyle : int8_t {
- /// Don't ensure spaces around pointer qualifiers and use PointerAlignment
- /// instead.
- /// \code
- /// PointerAlignment: Left PointerAlignment: Right
- /// void* const* x = NULL; vs. void *const *x = NULL;
- /// \endcode
- SAPQ_Default,
- /// Ensure that there is a space before pointer qualifiers.
- /// \code
- /// PointerAlignment: Left PointerAlignment: Right
- /// void* const* x = NULL; vs. void * const *x = NULL;
- /// \endcode
- SAPQ_Before,
- /// Ensure that there is a space after pointer qualifiers.
- /// \code
- /// PointerAlignment: Left PointerAlignment: Right
- /// void* const * x = NULL; vs. void *const *x = NULL;
- /// \endcode
- SAPQ_After,
- /// Ensure that there is a space both before and after pointer qualifiers.
- /// \code
- /// PointerAlignment: Left PointerAlignment: Right
- /// void* const * x = NULL; vs. void * const *x = NULL;
- /// \endcode
- SAPQ_Both,
- };
-
- /// Defines in which cases to put a space before or after pointer qualifiers
- /// \version 12
- SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers;
-
- /// If ``false``, spaces will be removed before assignment operators.
- /// \code
- /// true: false:
- /// int a = 5; vs. int a= 5;
- /// a += 42; a+= 42;
- /// \endcode
- /// \version 3.7
- bool SpaceBeforeAssignmentOperators;
-
- /// If ``false``, spaces will be removed before case colon.
- /// \code
- /// true: false
- /// switch (x) { vs. switch (x) {
- /// case 1 : break; case 1: break;
- /// } }
- /// \endcode
- /// \version 12
- bool SpaceBeforeCaseColon;
-
- /// If ``true``, a space will be inserted before a C++11 braced list
- /// used to initialize an object (after the preceding identifier or type).
- /// \code
- /// true: false:
- /// Foo foo { bar }; vs. Foo foo{ bar };
- /// Foo {}; Foo{};
- /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
- /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
- /// \endcode
- /// \version 7
- bool SpaceBeforeCpp11BracedList;
-
- /// If ``false``, spaces will be removed before constructor initializer
- /// colon.
- /// \code
- /// true: false:
- /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
- /// \endcode
- /// \version 7
- bool SpaceBeforeCtorInitializerColon;
-
- /// If ``false``, spaces will be removed before inheritance colon.
- /// \code
- /// true: false:
- /// class Foo : Bar {} vs. class Foo: Bar {}
- /// \endcode
- /// \version 7
- bool SpaceBeforeInheritanceColon;
-
- /// If ``true``, a space will be added before a JSON colon. For other
- /// languages, e.g. JavaScript, use ``SpacesInContainerLiterals`` instead.
- /// \code
- /// true: false:
- /// { {
- /// "key" : "value" vs. "key": "value"
- /// } }
- /// \endcode
- /// \version 17
- bool SpaceBeforeJsonColon;
-
- /// Different ways to put a space before opening parentheses.
- enum SpaceBeforeParensStyle : int8_t {
- /// This is **deprecated** and replaced by ``Custom`` below, with all
- /// ``SpaceBeforeParensOptions`` but ``AfterPlacementOperator`` set to
- /// ``false``.
- SBPO_Never,
- /// Put a space before opening parentheses only after control statement
- /// keywords (``for/if/while...``).
- /// \code
- /// void f() {
- /// if (true) {
- /// f();
- /// }
- /// }
- /// \endcode
- SBPO_ControlStatements,
- /// Same as ``SBPO_ControlStatements`` except this option doesn't apply to
- /// ForEach and If macros. This is useful in projects where ForEach/If
- /// macros are treated as function calls instead of control statements.
- /// ``SBPO_ControlStatementsExceptForEachMacros`` remains an alias for
- /// backward compatibility.
- /// \code
- /// void f() {
- /// Q_FOREACH(...) {
- /// f();
- /// }
- /// }
- /// \endcode
- SBPO_ControlStatementsExceptControlMacros,
- /// Put a space before opening parentheses only if the parentheses are not
- /// empty.
- /// \code
- /// void() {
- /// if (true) {
- /// f();
- /// g (x, y, z);
- /// }
- /// }
- /// \endcode
- SBPO_NonEmptyParentheses,
- /// Always put a space before opening parentheses, except when it's
- /// prohibited by the syntax rules (in function-like macro definitions) or
- /// when determined by other style rules (after unary operators, opening
- /// parentheses, etc.)
- /// \code
- /// void f () {
- /// if (true) {
- /// f ();
- /// }
- /// }
- /// \endcode
- SBPO_Always,
- /// Configure each individual space before parentheses in
- /// ``SpaceBeforeParensOptions``.
- SBPO_Custom,
- };
-
- /// Defines in which cases to put a space before opening parentheses.
- /// \version 3.5
- SpaceBeforeParensStyle SpaceBeforeParens;
-
- /// Precise control over the spacing before parentheses.
- /// \code
- /// # Should be declared this way:
- /// SpaceBeforeParens: Custom
- /// SpaceBeforeParensOptions:
- /// AfterControlStatements: true
- /// AfterFunctionDefinitionName: true
- /// \endcode
- struct SpaceBeforeParensCustom {
- /// If ``true``, put space between control statement keywords
- /// (for/if/while...) and opening parentheses.
- /// \code
- /// true: false:
- /// if (...) {} vs. if(...) {}
- /// \endcode
- bool AfterControlStatements;
- /// If ``true``, put space between foreach macros and opening parentheses.
- /// \code
- /// true: false:
- /// FOREACH (...) vs. FOREACH(...)
- /// <loop-body> <loop-body>
- /// \endcode
- bool AfterForeachMacros;
- /// If ``true``, put a space between function declaration name and opening
- /// parentheses.
- /// \code
- /// true: false:
- /// void f (); vs. void f();
- /// \endcode
- bool AfterFunctionDeclarationName;
- /// If ``true``, put a space between function definition name and opening
- /// parentheses.
- /// \code
- /// true: false:
- /// void f () {} vs. void f() {}
- /// \endcode
- bool AfterFunctionDefinitionName;
- /// If ``true``, put space between if macros and opening parentheses.
- /// \code
- /// true: false:
- /// IF (...) vs. IF(...)
- /// <conditional-body> <conditional-body>
- /// \endcode
- bool AfterIfMacros;
- /// If ``true``, put a space between alternative operator ``not`` and the
- /// opening parenthesis.
- /// \code
- /// true: false:
- /// return not (a || b); vs. return not(a || b);
- /// \endcode
- bool AfterNot;
- /// If ``true``, put a space between operator overloading and opening
- /// parentheses.
- /// \code
- /// true: false:
- /// void operator++ (int a); vs. void operator++(int a);
- /// object.operator++ (10); object.operator++(10);
- /// \endcode
- bool AfterOverloadedOperator;
- /// If ``true``, put a space between operator ``new``/``delete`` and opening
- /// parenthesis.
- /// \code
- /// true: false:
- /// new (buf) T; vs. new(buf) T;
- /// delete (buf) T; delete(buf) T;
- /// \endcode
- bool AfterPlacementOperator;
- /// If ``true``, put space between requires keyword in a requires clause and
- /// opening parentheses, if there is one.
- /// \code
- /// true: false:
- /// template<typename T> vs. template<typename T>
- /// requires (A<T> && B<T>) requires(A<T> && B<T>)
- /// ... ...
- /// \endcode
- bool AfterRequiresInClause;
- /// If ``true``, put space between requires keyword in a requires expression
- /// and opening parentheses.
- /// \code
- /// true: false:
- /// template<typename T> vs. template<typename T>
- /// concept C = requires (T t) { concept C = requires(T t) {
- /// ... ...
- /// } }
- /// \endcode
- bool AfterRequiresInExpression;
- /// If ``true``, put a space before opening parentheses only if the
- /// parentheses are not empty.
- /// \code
- /// true: false:
- /// void f (int a); vs. void f();
- /// f (a); f();
- /// \endcode
- bool BeforeNonEmptyParentheses;
-
- SpaceBeforeParensCustom()
- : AfterControlStatements(false), AfterForeachMacros(false),
- AfterFunctionDeclarationName(false),
- AfterFunctionDefinitionName(false), AfterIfMacros(false),
- AfterNot(false), AfterOverloadedOperator(false),
- AfterPlacementOperator(true), AfterRequiresInClause(false),
- AfterRequiresInExpression(false), BeforeNonEmptyParentheses(false) {}
-
- bool operator==(const SpaceBeforeParensCustom &Other) const {
- return AfterControlStatements == Other.AfterControlStatements &&
- AfterForeachMacros == Other.AfterForeachMacros &&
- AfterFunctionDeclarationName ==
- Other.AfterFunctionDeclarationName &&
- AfterFunctionDefinitionName == Other.AfterFunctionDefinitionName &&
- AfterIfMacros == Other.AfterIfMacros &&
- AfterNot == Other.AfterNot &&
- AfterOverloadedOperator == Other.AfterOverloadedOperator &&
- AfterPlacementOperator == Other.AfterPlacementOperator &&
- AfterRequiresInClause == Other.AfterRequiresInClause &&
- AfterRequiresInExpression == Other.AfterRequiresInExpression &&
- BeforeNonEmptyParentheses == Other.BeforeNonEmptyParentheses;
- }
- };
-
- /// Control of individual space before parentheses.
- ///
- /// If ``SpaceBeforeParens`` is set to ``Custom``, use this to specify
- /// how each individual space before parentheses case should be handled.
- /// Otherwise, this is ignored.
- /// \code{.yaml}
- /// # Example of usage:
- /// SpaceBeforeParens: Custom
- /// SpaceBeforeParensOptions:
- /// AfterControlStatements: true
- /// AfterFunctionDefinitionName: true
- /// \endcode
- /// \version 14
- SpaceBeforeParensCustom SpaceBeforeParensOptions;
-
- /// If ``true``, spaces will be before ``[``.
- /// Lambdas will not be affected. Only the first ``[`` will get a space added.
- /// \code
- /// true: false:
- /// int a [5]; vs. int a[5];
- /// int a [5][5]; vs. int a[5][5];
- /// \endcode
- /// \version 10
- bool SpaceBeforeSquareBrackets;
-
- /// If ``false``, spaces will be removed before range-based for loop
- /// colon.
- /// \code
- /// true: false:
- /// for (auto v : values) {} vs. for(auto v: values) {}
- /// \endcode
- /// \version 7
- bool SpaceBeforeRangeBasedForLoopColon;
-
- /// This option is **deprecated**. See ``Block`` of ``SpaceInEmptyBraces``.
- /// \version 10
- // bool SpaceInEmptyBlock;
-
- /// Style of when to insert a space in empty braces.
- enum SpaceInEmptyBracesStyle : int8_t {
- /// Always insert a space in empty braces.
- /// \code
- /// void f() { }
- /// class Unit { };
- /// auto a = [] { };
- /// int x{ };
- /// \endcode
- SIEB_Always,
- /// Only insert a space in empty blocks.
- /// \code
- /// void f() { }
- /// class Unit { };
- /// auto a = [] { };
- /// int x{};
- /// \endcode
- SIEB_Block,
- /// Never insert a space in empty braces.
- /// \code
- /// void f() {}
- /// class Unit {};
- /// auto a = [] {};
- /// int x{};
- /// \endcode
- SIEB_Never
- };
-
- /// Specifies when to insert a space in empty braces.
- /// \note
- /// This option doesn't apply to initializer braces if
- /// ``Cpp11BracedListStyle`` is not ``Block``.
- /// \endnote
- /// \version 22
- SpaceInEmptyBracesStyle SpaceInEmptyBraces;
-
- /// If ``true``, spaces may be inserted into ``()``.
- /// This option is **deprecated**. See ``InEmptyParentheses`` of
- /// ``SpacesInParensOptions``.
- /// \version 3.7
- // bool SpaceInEmptyParentheses;
-
- /// The number of spaces before trailing line comments
- /// (``//`` - comments).
- ///
- /// This does not affect trailing block comments (``/*`` - comments) as those
- /// commonly have different usage patterns and a number of special cases. In
- /// the case of Verilog, it doesn't affect a comment right after the opening
- /// parenthesis in the port or parameter list in a module header, because it
- /// is probably for the port on the following line instead of the parenthesis
- /// it follows.
- /// \code
- /// SpacesBeforeTrailingComments: 3
- /// void f() {
- /// if (true) { // foo1
- /// f(); // bar
- /// } // foo
- /// }
- /// \endcode
- /// \version 3.7
- unsigned SpacesBeforeTrailingComments;
-
- /// Styles for adding spacing after ``<`` and before ``>``
- /// in template argument lists.
- enum SpacesInAnglesStyle : int8_t {
- /// Remove spaces after ``<`` and before ``>``.
- /// \code
- /// static_cast<int>(arg);
- /// std::function<void(int)> fct;
- /// \endcode
- SIAS_Never,
- /// Add spaces after ``<`` and before ``>``.
- /// \code
- /// static_cast< int >(arg);
- /// std::function< void(int) > fct;
- /// \endcode
- SIAS_Always,
- /// Keep a single space after ``<`` and before ``>`` if any spaces were
- /// present. Option ``Standard: Cpp03`` takes precedence.
- SIAS_Leave
- };
- /// The SpacesInAnglesStyle to use for template argument lists.
- /// \version 3.4
- SpacesInAnglesStyle SpacesInAngles;
-
- /// If ``true``, spaces will be inserted around if/for/switch/while
- /// conditions.
- /// This option is **deprecated**. See ``InConditionalStatements`` of
- /// ``SpacesInParensOptions``.
- /// \version 10
- // bool SpacesInConditionalStatement;
-
- /// If ``true``, spaces are inserted inside container literals (e.g. ObjC and
- /// Javascript array and dict literals). For JSON, use
- /// ``SpaceBeforeJsonColon`` instead.
- /// \code{.js}
- /// true: false:
- /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
- /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
- /// \endcode
- /// \version 3.7
- bool SpacesInContainerLiterals;
-
- /// If ``true``, spaces may be inserted into C style casts.
- /// This option is **deprecated**. See ``InCStyleCasts`` of
- /// ``SpacesInParensOptions``.
- /// \version 3.7
- // bool SpacesInCStyleCastParentheses;
-
- /// Control of spaces within a single line comment.
- struct SpacesInLineComment {
- /// The minimum number of spaces at the start of the comment.
- unsigned Minimum;
- /// The maximum number of spaces at the start of the comment.
- unsigned Maximum;
- };
-
- /// How many spaces are allowed at the start of a line comment. To disable the
- /// maximum set it to ``-1``, apart from that the maximum takes precedence
- /// over the minimum.
- /// \code
- /// Minimum = 1
- /// Maximum = -1
- /// // One space is forced
- ///
- /// // but more spaces are possible
- ///
- /// Minimum = 0
- /// Maximum = 0
- /// //Forces to start every comment directly after the slashes
- /// \endcode
- ///
- /// Note that in line comment sections the relative indent of the subsequent
- /// lines is kept, that means the following:
- /// \code
- /// before: after:
- /// Minimum: 1
- /// //if (b) { // if (b) {
- /// // return true; // return true;
- /// //} // }
- ///
- /// Maximum: 0
- /// /// List: ///List:
- /// /// - Foo /// - Foo
- /// /// - Bar /// - Bar
- /// \endcode
- ///
- /// This option has only effect if ``ReflowComments`` is set to ``true``.
- /// \version 13
- SpacesInLineComment SpacesInLineCommentPrefix;
-
- /// Different ways to put a space before opening and closing parentheses.
- enum SpacesInParensStyle : int8_t {
- /// Never put a space in parentheses.
- /// \code
- /// void f() {
- /// if(true) {
- /// f();
- /// }
- /// }
- /// \endcode
- SIPO_Never,
- /// Configure each individual space in parentheses in
- /// `SpacesInParensOptions`.
- SIPO_Custom,
- };
-
- /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
- /// This option is **deprecated**. The previous behavior is preserved by using
- /// ``SpacesInParens`` with ``Custom`` and by setting all
- /// ``SpacesInParensOptions`` to ``true`` except for ``InCStyleCasts`` and
- /// ``InEmptyParentheses``.
- /// \version 3.7
- // bool SpacesInParentheses;
-
- /// Defines in which cases spaces will be inserted after ``(`` and before
- /// ``)``.
- /// \version 17
- SpacesInParensStyle SpacesInParens;
-
- /// Precise control over the spacing in parentheses.
- /// \code
- /// # Should be declared this way:
- /// SpacesInParens: Custom
- /// SpacesInParensOptions:
- /// ExceptDoubleParentheses: false
- /// InConditionalStatements: true
- /// Other: true
- /// \endcode
- struct SpacesInParensCustom {
- /// Override any of the following options to prevent addition of space
- /// when both opening and closing parentheses use multiple parentheses.
- /// \code
- /// true:
- /// __attribute__(( noreturn ))
- /// __decltype__(( x ))
- /// if (( a = b ))
- /// \endcode
- /// false:
- /// Uses the applicable option.
- bool ExceptDoubleParentheses;
- /// Put a space in parentheses only inside conditional statements
- /// (``for/if/while/switch...``).
- /// \code
- /// true: false:
- /// if ( a ) { ... } vs. if (a) { ... }
- /// while ( i < 5 ) { ... } while (i < 5) { ... }
- /// \endcode
- bool InConditionalStatements;
- /// Put a space in C style casts.
- /// \code
- /// true: false:
- /// x = ( int32 )y vs. x = (int32)y
- /// y = (( int (*)(int) )foo)(x); y = ((int (*)(int))foo)(x);
- /// \endcode
- bool InCStyleCasts;
- /// Insert a space in empty parentheses, i.e. ``()``.
- /// \code
- /// true: false:
- /// void f( ) { vs. void f() {
- /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
- /// if (true) { if (true) {
- /// f( ); f();
- /// } }
- /// } }
- /// \endcode
- bool InEmptyParentheses;
- /// Put a space in parentheses not covered by preceding options.
- /// \code
- /// true: false:
- /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
- /// \endcode
- bool Other;
-
- SpacesInParensCustom()
- : ExceptDoubleParentheses(false), InConditionalStatements(false),
- InCStyleCasts(false), InEmptyParentheses(false), Other(false) {}
-
- SpacesInParensCustom(bool ExceptDoubleParentheses,
- bool InConditionalStatements, bool InCStyleCasts,
- bool InEmptyParentheses, bool Other)
- : ExceptDoubleParentheses(ExceptDoubleParentheses),
- InConditionalStatements(InConditionalStatements),
- InCStyleCasts(InCStyleCasts), InEmptyParentheses(InEmptyParentheses),
- Other(Other) {}
-
- bool operator==(const SpacesInParensCustom &R) const {
- return ExceptDoubleParentheses == R.ExceptDoubleParentheses &&
- InConditionalStatements == R.InConditionalStatements &&
- InCStyleCasts == R.InCStyleCasts &&
- InEmptyParentheses == R.InEmptyParentheses && Other == R.Other;
- }
- bool operator!=(const SpacesInParensCustom &R) const {
- return !(*this == R);
- }
- };
-
- /// Control of individual spaces in parentheses.
- ///
- /// If ``SpacesInParens`` is set to ``Custom``, use this to specify
- /// how each individual space in parentheses case should be handled.
- /// Otherwise, this is ignored.
- /// \code{.yaml}
- /// # Example of usage:
- /// SpacesInParens: Custom
- /// SpacesInParensOptions:
- /// ExceptDoubleParentheses: false
- /// InConditionalStatements: true
- /// InEmptyParentheses: true
- /// \endcode
- /// \version 17
- SpacesInParensCustom SpacesInParensOptions;
-
- /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
- /// Lambdas without arguments or unspecified size array declarations will not
- /// be affected.
- /// \code
- /// true: false:
- /// int a[ 5 ]; vs. int a[5];
- /// std::unique_ptr<int[]> foo() {} // Won't be affected
- /// \endcode
- /// \version 3.7
- bool SpacesInSquareBrackets;
-
- /// Supported language standards for parsing and formatting C++ constructs.
- /// \code
- /// Latest: vector<set<int>>
- /// c++03 vs. vector<set<int> >
- /// \endcode
- ///
- /// The correct way to spell a specific language version is e.g. ``c++11``.
- /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
- enum LanguageStandard : int8_t {
- /// Parse and format as C++03.
- /// ``Cpp03`` is a deprecated alias for ``c++03``
- LS_Cpp03, // c++03
- /// Parse and format as C++11.
- LS_Cpp11, // c++11
- /// Parse and format as C++14.
- LS_Cpp14, // c++14
- /// Parse and format as C++17.
- LS_Cpp17, // c++17
- /// Parse and format as C++20.
- LS_Cpp20, // c++20
- /// Parse and format using the latest supported language version.
- /// ``Cpp11`` is a deprecated alias for ``Latest``
- LS_Latest,
- /// Automatic detection based on the input.
- LS_Auto,
- };
-
- /// Parse and format C++ constructs compatible with this standard.
- /// \code
- /// c++03: latest:
- /// vector<set<int> > x; vs. vector<set<int>> x;
- /// \endcode
- /// \version 3.7
- LanguageStandard Standard;
-
- /// Macros which are ignored in front of a statement, as if they were an
- /// attribute. So that they are not parsed as identifier, for example for Qts
- /// emit.
- /// \code
- /// AlignConsecutiveDeclarations: true
- /// StatementAttributeLikeMacros: []
- /// unsigned char data = 'x';
- /// emit signal(data); // This is parsed as variable declaration.
- ///
- /// AlignConsecutiveDeclarations: true
- /// StatementAttributeLikeMacros: [emit]
- /// unsigned char data = 'x';
- /// emit signal(data); // Now it's fine again.
- /// \endcode
- /// \version 12
- std::vector<std::string> StatementAttributeLikeMacros;
-
- /// A vector of macros that should be interpreted as complete statements.
- ///
- /// Typical macros are expressions and require a semicolon to be added.
- /// Sometimes this is not the case, and this allows to make clang-format aware
- /// of such cases.
- ///
- /// For example: Q_UNUSED
- /// \version 8
- std::vector<std::string> StatementMacros;
-
- /// Works only when TableGenBreakInsideDAGArg is not DontBreak.
- /// The string list needs to consist of identifiers in TableGen.
- /// If any identifier is specified, this limits the line breaks by
- /// TableGenBreakInsideDAGArg option only on DAGArg values beginning with
- /// the specified identifiers.
- ///
- /// For example the configuration,
- /// \code{.yaml}
- /// TableGenBreakInsideDAGArg: BreakAll
- /// TableGenBreakingDAGArgOperators: [ins, outs]
- /// \endcode
- ///
- /// makes the line break only occurs inside DAGArgs beginning with the
- /// specified identifiers ``ins`` and ``outs``.
- ///
- /// \code
- /// let DAGArgIns = (ins
- /// i32:$src1,
- /// i32:$src2
- /// );
- /// let DAGArgOtherID = (other i32:$other1, i32:$other2);
- /// let DAGArgBang = (!cast<SomeType>("Some") i32:$src1, i32:$src2)
- /// \endcode
- /// \version 19
- std::vector<std::string> TableGenBreakingDAGArgOperators;
-
- /// Different ways to control the format inside TableGen DAGArg.
- enum DAGArgStyle : int8_t {
- /// Never break inside DAGArg.
- /// \code
- /// let DAGArgIns = (ins i32:$src1, i32:$src2);
- /// \endcode
- DAS_DontBreak,
- /// Break inside DAGArg after each list element but for the last.
- /// This aligns to the first element.
- /// \code
- /// let DAGArgIns = (ins i32:$src1,
- /// i32:$src2);
- /// \endcode
- DAS_BreakElements,
- /// Break inside DAGArg after the operator and the all elements.
- /// \code
- /// let DAGArgIns = (ins
- /// i32:$src1,
- /// i32:$src2
- /// );
- /// \endcode
- DAS_BreakAll,
- };
-
- /// The styles of the line break inside the DAGArg in TableGen.
- /// \version 19
- DAGArgStyle TableGenBreakInsideDAGArg;
-
- /// The number of columns used for tab stops.
- /// \version 3.7
- unsigned TabWidth;
-
- /// A vector of non-keyword identifiers that should be interpreted as template
- /// names.
- ///
- /// A ``<`` after a template name is annotated as a template opener instead of
- /// a binary operator.
- ///
- /// \version 20
- std::vector<std::string> TemplateNames;
-
- /// A vector of non-keyword identifiers that should be interpreted as type
- /// names.
- ///
- /// A ``*``, ``&``, or ``&&`` between a type name and another non-keyword
- /// identifier is annotated as a pointer or reference token instead of a
- /// binary operator.
- ///
- /// \version 17
- std::vector<std::string> TypeNames;
-
- /// A vector of macros that should be interpreted as type declarations instead
- /// of as function calls.
- ///
- /// These are expected to be macros of the form:
- /// \code
- /// STACK_OF(...)
- /// \endcode
- ///
- /// In the .clang-format configuration file, this can be configured like:
- /// \code{.yaml}
- /// TypenameMacros: [STACK_OF, LIST]
- /// \endcode
- ///
- /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
- /// \version 9
- std::vector<std::string> TypenameMacros;
-
- /// This option is **deprecated**. See ``LF`` and ``CRLF`` of ``LineEnding``.
- /// \version 10
- // bool UseCRLF;
-
- /// Different ways to use tab in formatting.
- enum UseTabStyle : int8_t {
- /// Never use tab.
- UT_Never,
- /// Use tabs only for indentation.
- UT_ForIndentation,
- /// Fill all leading whitespace with tabs, and use spaces for alignment that
- /// appears within a line (e.g. consecutive assignments and declarations).
- UT_ForContinuationAndIndentation,
- /// Use tabs for line continuation and indentation, and spaces for
- /// alignment.
- UT_AlignWithSpaces,
- /// Use tabs whenever we need to fill whitespace that spans at least from
- /// one tab stop to the next one.
- UT_Always
- };
-
- /// The way to use tab characters in the resulting file.
- /// \version 3.7
- UseTabStyle UseTab;
-
- /// A vector of non-keyword identifiers that should be interpreted as variable
- /// template names.
- ///
- /// A ``)`` after a variable template instantiation is **not** annotated as
- /// the closing parenthesis of C-style cast operator.
- ///
- /// \version 20
- std::vector<std::string> VariableTemplates;
-
- /// For Verilog, put each port on its own line in module instantiations.
- /// \code
- /// true:
- /// ffnand ff1(.q(),
- /// .qbar(out1),
- /// .clear(in1),
- /// .preset(in2));
- ///
- /// false:
- /// ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));
- /// \endcode
- /// \version 17
- bool VerilogBreakBetweenInstancePorts;
-
- /// A vector of macros which are whitespace-sensitive and should not
- /// be touched.
- ///
- /// These are expected to be macros of the form:
- /// \code
- /// STRINGIZE(...)
- /// \endcode
- ///
- /// In the .clang-format configuration file, this can be configured like:
- /// \code{.yaml}
- /// WhitespaceSensitiveMacros: [STRINGIZE, PP_STRINGIZE]
- /// \endcode
- ///
- /// For example: BOOST_PP_STRINGIZE
- /// \version 11
- std::vector<std::string> WhitespaceSensitiveMacros;
-
- /// Different styles for wrapping namespace body with empty lines.
- enum WrapNamespaceBodyWithEmptyLinesStyle : int8_t {
- /// Remove all empty lines at the beginning and the end of namespace body.
- /// \code
- /// namespace N1 {
- /// namespace N2 {
- /// function();
- /// }
- /// }
- /// \endcode
- WNBWELS_Never,
- /// Always have at least one empty line at the beginning and the end of
- /// namespace body except that the number of empty lines between consecutive
- /// nested namespace definitions is not increased.
- /// \code
- /// namespace N1 {
- /// namespace N2 {
- ///
- /// function();
- ///
- /// }
- /// }
- /// \endcode
- WNBWELS_Always,
- /// Keep existing newlines at the beginning and the end of namespace body.
- /// ``MaxEmptyLinesToKeep`` still applies.
- WNBWELS_Leave
- };
-
- /// Wrap namespace body with empty lines.
- /// \version 20
- WrapNamespaceBodyWithEmptyLinesStyle WrapNamespaceBodyWithEmptyLines;
-
- bool operator==(const FormatStyle &R) const {
- return AccessModifierOffset == R.AccessModifierOffset &&
- AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
- AlignArrayOfStructures == R.AlignArrayOfStructures &&
- AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
- AlignConsecutiveBitFields == R.AlignConsecutiveBitFields &&
- AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
- AlignConsecutiveMacros == R.AlignConsecutiveMacros &&
- AlignConsecutiveShortCaseStatements ==
- R.AlignConsecutiveShortCaseStatements &&
- AlignConsecutiveTableGenBreakingDAGArgColons ==
- R.AlignConsecutiveTableGenBreakingDAGArgColons &&
- AlignConsecutiveTableGenCondOperatorColons ==
- R.AlignConsecutiveTableGenCondOperatorColons &&
- AlignConsecutiveTableGenDefinitionColons ==
- R.AlignConsecutiveTableGenDefinitionColons &&
- AlignEscapedNewlines == R.AlignEscapedNewlines &&
- AlignOperands == R.AlignOperands &&
- AlignTrailingComments == R.AlignTrailingComments &&
- AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
- AllowAllParametersOfDeclarationOnNextLine ==
- R.AllowAllParametersOfDeclarationOnNextLine &&
- AllowBreakBeforeNoexceptSpecifier ==
- R.AllowBreakBeforeNoexceptSpecifier &&
- AllowBreakBeforeQtProperty == R.AllowBreakBeforeQtProperty &&
- AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
- AllowShortCaseExpressionOnASingleLine ==
- R.AllowShortCaseExpressionOnASingleLine &&
- AllowShortCaseLabelsOnASingleLine ==
- R.AllowShortCaseLabelsOnASingleLine &&
- AllowShortCompoundRequirementOnASingleLine ==
- R.AllowShortCompoundRequirementOnASingleLine &&
- AllowShortEnumsOnASingleLine == R.AllowShortEnumsOnASingleLine &&
- AllowShortFunctionsOnASingleLine ==
- R.AllowShortFunctionsOnASingleLine &&
- AllowShortIfStatementsOnASingleLine ==
- R.AllowShortIfStatementsOnASingleLine &&
- AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
- AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
- AllowShortNamespacesOnASingleLine ==
- R.AllowShortNamespacesOnASingleLine &&
- AllowShortRecordOnASingleLine == R.AllowShortRecordOnASingleLine &&
- AlwaysBreakBeforeMultilineStrings ==
- R.AlwaysBreakBeforeMultilineStrings &&
- AttributeMacros == R.AttributeMacros &&
- BinPackArguments == R.BinPackArguments &&
- BinPackLongBracedList == R.BinPackLongBracedList &&
- BinPackParameters == R.BinPackParameters &&
- BitFieldColonSpacing == R.BitFieldColonSpacing &&
- BracedInitializerIndentWidth == R.BracedInitializerIndentWidth &&
- BreakAdjacentStringLiterals == R.BreakAdjacentStringLiterals &&
- BreakAfterAttributes == R.BreakAfterAttributes &&
- BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
- BreakAfterOpenBracketBracedList ==
- R.BreakAfterOpenBracketBracedList &&
- BreakAfterOpenBracketFunction == R.BreakAfterOpenBracketFunction &&
- BreakAfterOpenBracketIf == R.BreakAfterOpenBracketIf &&
- BreakAfterOpenBracketLoop == R.BreakAfterOpenBracketLoop &&
- BreakAfterOpenBracketSwitch == R.BreakAfterOpenBracketSwitch &&
- BreakAfterReturnType == R.BreakAfterReturnType &&
- BreakArrays == R.BreakArrays &&
- BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
- BreakBeforeBraces == R.BreakBeforeBraces &&
- BreakBeforeCloseBracketBracedList ==
- R.BreakBeforeCloseBracketBracedList &&
- BreakBeforeCloseBracketFunction ==
- R.BreakBeforeCloseBracketFunction &&
- BreakBeforeCloseBracketIf == R.BreakBeforeCloseBracketIf &&
- BreakBeforeCloseBracketLoop == R.BreakBeforeCloseBracketLoop &&
- BreakBeforeCloseBracketSwitch == R.BreakBeforeCloseBracketSwitch &&
- BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations &&
- BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
- BreakBeforeTemplateCloser == R.BreakBeforeTemplateCloser &&
- BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
- BreakBinaryOperations == R.BreakBinaryOperations &&
- BreakConstructorInitializers == R.BreakConstructorInitializers &&
- BreakFunctionDefinitionParameters ==
- R.BreakFunctionDefinitionParameters &&
- BreakInheritanceList == R.BreakInheritanceList &&
- BreakStringLiterals == R.BreakStringLiterals &&
- BreakTemplateDeclarations == R.BreakTemplateDeclarations &&
- ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
- CompactNamespaces == R.CompactNamespaces &&
- ConstructorInitializerIndentWidth ==
- R.ConstructorInitializerIndentWidth &&
- ContinuationIndentWidth == R.ContinuationIndentWidth &&
- Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
- DerivePointerAlignment == R.DerivePointerAlignment &&
- DisableFormat == R.DisableFormat &&
- EmptyLineAfterAccessModifier == R.EmptyLineAfterAccessModifier &&
- EmptyLineBeforeAccessModifier == R.EmptyLineBeforeAccessModifier &&
- EnumTrailingComma == R.EnumTrailingComma &&
- ExperimentalAutoDetectBinPacking ==
- R.ExperimentalAutoDetectBinPacking &&
- FixNamespaceComments == R.FixNamespaceComments &&
- ForEachMacros == R.ForEachMacros &&
- IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
- IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
- IncludeStyle.IncludeIsMainRegex ==
- R.IncludeStyle.IncludeIsMainRegex &&
- IncludeStyle.IncludeIsMainSourceRegex ==
- R.IncludeStyle.IncludeIsMainSourceRegex &&
- IncludeStyle.MainIncludeChar == R.IncludeStyle.MainIncludeChar &&
- IndentAccessModifiers == R.IndentAccessModifiers &&
- IndentCaseBlocks == R.IndentCaseBlocks &&
- IndentCaseLabels == R.IndentCaseLabels &&
- IndentExportBlock == R.IndentExportBlock &&
- IndentExternBlock == R.IndentExternBlock &&
- IndentGotoLabels == R.IndentGotoLabels &&
- IndentPPDirectives == R.IndentPPDirectives &&
- IndentRequiresClause == R.IndentRequiresClause &&
- IndentWidth == R.IndentWidth &&
- IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
- InsertBraces == R.InsertBraces &&
- InsertNewlineAtEOF == R.InsertNewlineAtEOF &&
- IntegerLiteralSeparator == R.IntegerLiteralSeparator &&
- JavaImportGroups == R.JavaImportGroups &&
- JavaScriptQuotes == R.JavaScriptQuotes &&
- JavaScriptWrapImports == R.JavaScriptWrapImports &&
- KeepEmptyLines == R.KeepEmptyLines &&
- KeepFormFeed == R.KeepFormFeed && Language == R.Language &&
- LambdaBodyIndentation == R.LambdaBodyIndentation &&
- LineEnding == R.LineEnding && MacroBlockBegin == R.MacroBlockBegin &&
- MacroBlockEnd == R.MacroBlockEnd && Macros == R.Macros &&
- MacrosSkippedByRemoveParentheses ==
- R.MacrosSkippedByRemoveParentheses &&
- MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
- NamespaceIndentation == R.NamespaceIndentation &&
- NamespaceMacros == R.NamespaceMacros &&
- NumericLiteralCase == R.NumericLiteralCase &&
- ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
- ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
- ObjCBreakBeforeNestedBlockParam ==
- R.ObjCBreakBeforeNestedBlockParam &&
- ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder &&
- ObjCSpaceAfterMethodDeclarationPrefix ==
- R.ObjCSpaceAfterMethodDeclarationPrefix &&
- ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
- ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
- OneLineFormatOffRegex == R.OneLineFormatOffRegex &&
- PackConstructorInitializers == R.PackConstructorInitializers &&
- PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
- PenaltyBreakBeforeFirstCallParameter ==
- R.PenaltyBreakBeforeFirstCallParameter &&
- PenaltyBreakBeforeMemberAccess == R.PenaltyBreakBeforeMemberAccess &&
- PenaltyBreakComment == R.PenaltyBreakComment &&
- PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
- PenaltyBreakOpenParenthesis == R.PenaltyBreakOpenParenthesis &&
- PenaltyBreakScopeResolution == R.PenaltyBreakScopeResolution &&
- PenaltyBreakString == R.PenaltyBreakString &&
- PenaltyBreakTemplateDeclaration ==
- R.PenaltyBreakTemplateDeclaration &&
- PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
- PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
- PointerAlignment == R.PointerAlignment &&
- QualifierAlignment == R.QualifierAlignment &&
- QualifierOrder == R.QualifierOrder &&
- RawStringFormats == R.RawStringFormats &&
- ReferenceAlignment == R.ReferenceAlignment &&
- RemoveBracesLLVM == R.RemoveBracesLLVM &&
- RemoveEmptyLinesInUnwrappedLines ==
- R.RemoveEmptyLinesInUnwrappedLines &&
- RemoveParentheses == R.RemoveParentheses &&
- RemoveSemicolon == R.RemoveSemicolon &&
- RequiresClausePosition == R.RequiresClausePosition &&
- RequiresExpressionIndentation == R.RequiresExpressionIndentation &&
- SeparateDefinitionBlocks == R.SeparateDefinitionBlocks &&
- ShortNamespaceLines == R.ShortNamespaceLines &&
- SkipMacroDefinitionBody == R.SkipMacroDefinitionBody &&
- SortIncludes == R.SortIncludes &&
- SortJavaStaticImport == R.SortJavaStaticImport &&
- SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
- SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
- SpaceAfterOperatorKeyword == R.SpaceAfterOperatorKeyword &&
- SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
- SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
- SpaceBeforeCaseColon == R.SpaceBeforeCaseColon &&
- SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
- SpaceBeforeCtorInitializerColon ==
- R.SpaceBeforeCtorInitializerColon &&
- SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
- SpaceBeforeJsonColon == R.SpaceBeforeJsonColon &&
- SpaceBeforeParens == R.SpaceBeforeParens &&
- SpaceBeforeParensOptions == R.SpaceBeforeParensOptions &&
- SpaceAroundPointerQualifiers == R.SpaceAroundPointerQualifiers &&
- SpaceBeforeRangeBasedForLoopColon ==
- R.SpaceBeforeRangeBasedForLoopColon &&
- SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
- SpaceInEmptyBraces == R.SpaceInEmptyBraces &&
- SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
- SpacesInAngles == R.SpacesInAngles &&
- SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
- SpacesInLineCommentPrefix.Minimum ==
- R.SpacesInLineCommentPrefix.Minimum &&
- SpacesInLineCommentPrefix.Maximum ==
- R.SpacesInLineCommentPrefix.Maximum &&
- SpacesInParens == R.SpacesInParens &&
- SpacesInParensOptions == R.SpacesInParensOptions &&
- SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
- Standard == R.Standard &&
- StatementAttributeLikeMacros == R.StatementAttributeLikeMacros &&
- StatementMacros == R.StatementMacros &&
- TableGenBreakingDAGArgOperators ==
- R.TableGenBreakingDAGArgOperators &&
- TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
- TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
- TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
- UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
- VerilogBreakBetweenInstancePorts ==
- R.VerilogBreakBetweenInstancePorts &&
- WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros &&
- WrapNamespaceBodyWithEmptyLines == R.WrapNamespaceBodyWithEmptyLines;
- }
-
- std::optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
-
- // Stores per-language styles. A FormatStyle instance inside has an empty
- // StyleSet. A FormatStyle instance returned by the Get method has its
- // StyleSet set to a copy of the originating StyleSet, effectively keeping the
- // internal representation of that StyleSet alive.
- //
- // The memory management and ownership reminds of a birds nest: chicks
- // leaving the nest take photos of the nest with them.
- struct FormatStyleSet {
- typedef std::map<LanguageKind, FormatStyle> MapType;
-
- std::optional<FormatStyle> Get(LanguageKind Language) const;
-
- // Adds \p Style to this FormatStyleSet. Style must not have an associated
- // FormatStyleSet.
- // Style.Language should be different than LK_None. If this FormatStyleSet
- // already contains an entry for Style.Language, that gets replaced with the
- // passed Style.
- void Add(FormatStyle Style);
-
- // Clears this FormatStyleSet.
- void Clear();
-
- private:
- std::shared_ptr<MapType> Styles;
- };
-
- static FormatStyleSet BuildStyleSetFromConfiguration(
- const FormatStyle &MainStyle,
- const std::vector<FormatStyle> &ConfigurationStyles);
-
-private:
- FormatStyleSet StyleSet;
-
- friend std::error_code
- parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style,
- bool AllowUnknownOptions,
- llvm::SourceMgr::DiagHandlerTy DiagHandler,
- void *DiagHandlerCtxt, bool IsDotHFile);
-};
-
-/// Returns a format style complying with the LLVM coding standards:
-/// http://llvm.org/docs/CodingStandards.html.
-FormatStyle
-getLLVMStyle(FormatStyle::LanguageKind Language = FormatStyle::LK_Cpp);
-
-/// Returns a format style complying with one of Google's style guides:
-/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
-/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
-/// https://developers.google.com/protocol-buffers/docs/style.
-FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
-
-/// Returns a format style complying with Chromium's style guide:
-/// http://www.chromium.org/developers/coding-style.
-FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
-
-/// Returns a format style complying with Mozilla's style guide:
-/// https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html.
-FormatStyle getMozillaStyle();
-
-/// Returns a format style complying with Webkit's style guide:
-/// http://www.webkit.org/coding/coding-style.html
-FormatStyle getWebKitStyle();
-
-/// Returns a format style complying with GNU Coding Standards:
-/// http://www.gnu.org/prep/standards/standards.html
-FormatStyle getGNUStyle();
-
-/// Returns a format style complying with Microsoft style guide:
-/// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
-FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language);
-
-FormatStyle getClangFormatStyle();
-
-/// Returns style indicating formatting should be not applied at all.
-FormatStyle getNoStyle();
-
-/// Gets a predefined style for the specified language by name.
-///
-/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
-/// compared case-insensitively.
-///
-/// Returns ``true`` if the Style has been set.
-bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
- FormatStyle *Style);
-
-/// Parse configuration from YAML-formatted text.
-///
-/// Style->Language is used to get the base style, if the ``BasedOnStyle``
-/// option is present.
-///
-/// The FormatStyleSet of Style is reset.
-///
-/// When ``BasedOnStyle`` is not present, options not present in the YAML
-/// document, are retained in \p Style.
-///
-/// If AllowUnknownOptions is true, no errors are emitted if unknown
-/// format options are occurred.
-///
-/// If set all diagnostics are emitted through the DiagHandler.
-std::error_code
-parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style,
- bool AllowUnknownOptions = false,
- llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
- void *DiagHandlerCtx = nullptr, bool IsDotHFile = false);
-
-/// Like above but accepts an unnamed buffer.
-inline std::error_code parseConfiguration(StringRef Config, FormatStyle *Style,
- bool AllowUnknownOptions = false,
- bool IsDotHFile = false) {
- return parseConfiguration(llvm::MemoryBufferRef(Config, "YAML"), Style,
- AllowUnknownOptions, /*DiagHandler=*/nullptr,
- /*DiagHandlerCtx=*/nullptr, IsDotHFile);
-}
-
-/// Gets configuration in a YAML string.
-std::string configurationAsText(const FormatStyle &Style);
-
-/// Returns the replacements necessary to sort all ``#include`` blocks
-/// that are affected by ``Ranges``.
-tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName,
- unsigned *Cursor = nullptr);
-
-/// Returns the replacements corresponding to applying and formatting
-/// \p Replaces on success; otheriwse, return an llvm::Error carrying
-/// llvm::StringError.
-Expected<tooling::Replacements>
-formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
- const FormatStyle &Style);
-
-/// Returns the replacements corresponding to applying \p Replaces and
-/// cleaning up the code after that on success; otherwise, return an llvm::Error
-/// carrying llvm::StringError.
-/// This also supports inserting/deleting C++ #include directives:
-/// * If a replacement has offset UINT_MAX, length 0, and a replacement text
-/// that is an #include directive, this will insert the #include into the
-/// correct block in the \p Code.
-/// * If a replacement has offset UINT_MAX, length 1, and a replacement text
-/// that is the name of the header to be removed, the header will be removed
-/// from \p Code if it exists.
-/// The include manipulation is done via ``tooling::HeaderInclude``, see its
-/// documentation for more details on how include insertion points are found and
-/// what edits are produced.
-Expected<tooling::Replacements>
-cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
- const FormatStyle &Style);
-
-/// Represents the status of a formatting attempt.
-struct FormattingAttemptStatus {
- /// A value of ``false`` means that any of the affected ranges were not
- /// formatted due to a non-recoverable syntax error.
- bool FormatComplete = true;
-
- /// If ``FormatComplete`` is false, ``Line`` records a one-based
- /// original line number at which a syntax error might have occurred. This is
- /// based on a best-effort analysis and could be imprecise.
- unsigned Line = 0;
-};
-
-/// Reformats the given \p Ranges in \p Code.
-///
-/// Each range is extended on either end to its next bigger logic unit, i.e.
-/// everything that might influence its formatting or might be influenced by its
-/// formatting.
-///
-/// Returns the ``Replacements`` necessary to make all \p Ranges comply with
-/// \p Style.
-///
-/// If ``Status`` is non-null, its value will be populated with the status of
-/// this formatting attempt. See \c FormattingAttemptStatus.
-tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName = "<stdin>",
- FormattingAttemptStatus *Status = nullptr);
-
-/// Same as above, except if ``IncompleteFormat`` is non-null, its value
-/// will be set to true if any of the affected ranges were not formatted due to
-/// a non-recoverable syntax error.
-tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName, bool *IncompleteFormat);
-
-/// Clean up any erroneous/redundant code in the given \p Ranges in \p
-/// Code.
-///
-/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
-tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName = "<stdin>");
-
-/// Fix namespace end comments in the given \p Ranges in \p Code.
-///
-/// Returns the ``Replacements`` that fix the namespace comments in all
-/// \p Ranges in \p Code.
-tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
- StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName = "<stdin>");
-
-/// Inserts or removes empty lines separating definition blocks including
-/// classes, structs, functions, namespaces, and enums in the given \p Ranges in
-/// \p Code.
-///
-/// Returns the ``Replacements`` that inserts or removes empty lines separating
-/// definition blocks in all \p Ranges in \p Code.
-tooling::Replacements separateDefinitionBlocks(const FormatStyle &Style,
- StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName = "<stdin>");
-
-/// Sort consecutive using declarations in the given \p Ranges in
-/// \p Code.
-///
-/// Returns the ``Replacements`` that sort the using declarations in all
-/// \p Ranges in \p Code.
-tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
- StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName = "<stdin>");
-
-/// Returns the ``LangOpts`` that the formatter expects you to set.
-///
-/// \param Style determines specific settings for lexing mode.
-LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
-
-/// Description to be used for help text for a ``llvm::cl`` option for
-/// specifying format style. The description is closely related to the operation
-/// of ``getStyle()``.
-extern const char *StyleOptionHelpDescription;
-
-/// The suggested format style to use by default. This allows tools using
-/// ``getStyle`` to have a consistent default style.
-/// Different builds can modify the value to the preferred styles.
-extern const char *DefaultFormatStyle;
-
-/// The suggested predefined style to use as the fallback style in ``getStyle``.
-/// Different builds can modify the value to the preferred styles.
-extern const char *DefaultFallbackStyle;
-
-/// Construct a FormatStyle based on ``StyleName``.
-///
-/// ``StyleName`` can take several forms:
-/// * "{<key>: <value>, ...}" - Set specic style parameters.
-/// * "<style name>" - One of the style names supported by getPredefinedStyle().
-/// * "file" - Load style configuration from a file called ``.clang-format``
-/// located in one of the parent directories of ``FileName`` or the current
-/// directory if ``FileName`` is empty.
-/// * "file:<format_file_path>" to explicitly specify the configuration file to
-/// use.
-///
-/// \param[in] StyleName Style name to interpret according to the description
-/// above.
-/// \param[in] FileName Path to start search for .clang-format if ``StyleName``
-/// == "file".
-/// \param[in] FallbackStyle The name of a predefined style used to fallback to
-/// in case \p StyleName is "file" and no file can be found.
-/// \param[in] Code The actual code to be formatted. Used to determine the
-/// language if the filename isn't sufficient.
-/// \param[in] FS The underlying file system, in which the file resides. By
-/// default, the file system is the real file system.
-/// \param[in] AllowUnknownOptions If true, unknown format options only
-/// emit a warning. If false, errors are emitted on unknown format
-/// options.
-///
-/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
-/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
-/// determined, returns an Error.
-Expected<FormatStyle>
-getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
- StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
- bool AllowUnknownOptions = false,
- llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
-
-// Guesses the language from the ``FileName`` and ``Code`` to be formatted.
-// Defaults to FormatStyle::LK_Cpp.
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
-
-// Returns a string representation of ``Language``.
-inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
- switch (Language) {
- case FormatStyle::LK_C:
- return "C";
- case FormatStyle::LK_Cpp:
- return "C++";
- case FormatStyle::LK_CSharp:
- return "CSharp";
- case FormatStyle::LK_ObjC:
- return "Objective-C";
- case FormatStyle::LK_Java:
- return "Java";
- case FormatStyle::LK_JavaScript:
- return "JavaScript";
- case FormatStyle::LK_Json:
- return "Json";
- case FormatStyle::LK_Proto:
- return "Proto";
- case FormatStyle::LK_TableGen:
- return "TableGen";
- case FormatStyle::LK_TextProto:
- return "TextProto";
- case FormatStyle::LK_Verilog:
- return "Verilog";
- default:
- return "Unknown";
- }
-}
-
-bool isClangFormatOn(StringRef Comment);
-bool isClangFormatOff(StringRef Comment);
-
-} // end namespace format
-} // end namespace clang
-
-template <>
-struct std::is_error_code_enum<clang::format::ParseError> : std::true_type {};
-
-#endif // LLVM_CLANG_FORMAT_FORMAT_H
+//===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Various functions to configurably format source code.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_FORMAT_FORMAT_H
+#define LLVM_CLANG_FORMAT_FORMAT_H
+
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Inclusions/IncludeStyle.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/SourceMgr.h"
+#include <optional>
+#include <system_error>
+
+namespace llvm {
+namespace vfs {
+class FileSystem;
+}
+} // namespace llvm
+
+namespace clang {
+namespace format {
+
+enum class ParseError {
+ Success = 0,
+ Error,
+ Unsuitable,
+ BinPackTrailingCommaConflict,
+ InvalidQualifierSpecified,
+ DuplicateQualifierSpecified,
+ MissingQualifierType,
+ MissingQualifierOrder
+};
+class ParseErrorCategory final : public std::error_category {
+public:
+ const char *name() const noexcept override;
+ std::string message(int EV) const override;
+};
+const std::error_category &getParseCategory();
+std::error_code make_error_code(ParseError e);
+
+/// The ``FormatStyle`` is used to configure the formatting to follow
+/// specific guidelines.
+struct FormatStyle {
+ // If the BasedOn: was InheritParentConfig and this style needs the file from
+ // the parent directories. It is not part of the actual style for formatting.
+ // Thus the // instead of ///.
+ std::string InheritConfig;
+
+ /// The extra indent or outdent of access modifiers, e.g. ``public:``.
+ /// \version 3.3
+ int AccessModifierOffset;
+
+ /// If ``true``, horizontally aligns arguments after an open bracket.
+ ///
+ /// \code
+ /// true: vs. false
+ /// someLongFunction(argument1, someLongFunction(argument1,
+ /// argument2); argument2);
+ /// \endcode
+ ///
+ /// \note
+ /// As of clang-format 22 this option is a bool with the previous
+ /// option of ``Align`` replaced with ``true``, ``DontAlign`` replaced
+ /// with ``false``, and the options of ``AlwaysBreak`` and ``BlockIndent``
+ /// replaced with ``true`` and with setting of new style options using
+ /// ``BreakAfterOpenBracketBracedList``, ``BreakAfterOpenBracketFunction``,
+ /// ``BreakAfterOpenBracketIf``, ``BreakBeforeCloseBracketBracedList``,
+ /// ``BreakBeforeCloseBracketFunction``, and ``BreakBeforeCloseBracketIf``.
+ /// \endnote
+ ///
+ /// This applies to round brackets (parentheses), angle brackets and square
+ /// brackets.
+ /// \version 3.8
+ bool AlignAfterOpenBracket;
+
+ /// Different style for aligning array initializers.
+ enum ArrayInitializerAlignmentStyle : int8_t {
+ /// Align array column and left justify the columns e.g.:
+ /// \code
+ /// struct test demo[] =
+ /// {
+ /// {56, 23, "hello"},
+ /// {-1, 93463, "world"},
+ /// {7, 5, "!!" }
+ /// };
+ /// \endcode
+ AIAS_Left,
+ /// Align array column and right justify the columns e.g.:
+ /// \code
+ /// struct test demo[] =
+ /// {
+ /// {56, 23, "hello"},
+ /// {-1, 93463, "world"},
+ /// { 7, 5, "!!"}
+ /// };
+ /// \endcode
+ AIAS_Right,
+ /// Don't align array initializer columns.
+ AIAS_None
+ };
+ /// If not ``None``, when using initialization for an array of structs
+ /// aligns the fields into columns.
+ ///
+ /// \note
+ /// As of clang-format 15 this option only applied to arrays with equal
+ /// number of columns per row.
+ /// \endnote
+ ///
+ /// \version 13
+ ArrayInitializerAlignmentStyle AlignArrayOfStructures;
+
+ /// Alignment options.
+ ///
+ /// They can also be read as a whole for compatibility. The choices are:
+ ///
+ /// * ``None``
+ /// * ``Consecutive``
+ /// * ``AcrossEmptyLines``
+ /// * ``AcrossComments``
+ /// * ``AcrossEmptyLinesAndComments``
+ ///
+ /// For example, to align across empty lines and not across comments, either
+ /// of these work.
+ /// \code
+ /// <option-name>: AcrossEmptyLines
+ ///
+ /// <option-name>:
+ /// Enabled: true
+ /// AcrossEmptyLines: true
+ /// AcrossComments: false
+ /// \endcode
+ struct AlignConsecutiveStyle {
+ /// Whether aligning is enabled.
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ /// #define foo(x) (x * x)
+ /// #define bar(y, z) (y + z)
+ ///
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ ///
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ /// \endcode
+ bool Enabled;
+ /// Whether to align across empty lines.
+ /// \code
+ /// true:
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ ///
+ /// false:
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ /// \endcode
+ bool AcrossEmptyLines;
+ /// Whether to align across comments.
+ /// \code
+ /// true:
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ ///
+ /// false:
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ /// \endcode
+ bool AcrossComments;
+ /// Only for ``AlignConsecutiveAssignments``. Whether compound assignments
+ /// like ``+=`` are aligned along with ``=``.
+ /// \code
+ /// true:
+ /// a &= 2;
+ /// bbb = 2;
+ ///
+ /// false:
+ /// a &= 2;
+ /// bbb = 2;
+ /// \endcode
+ bool AlignCompound;
+ /// Only for ``AlignConsecutiveDeclarations``. Whether function declarations
+ /// are aligned.
+ /// \code
+ /// true:
+ /// unsigned int f1(void);
+ /// void f2(void);
+ /// size_t f3(void);
+ ///
+ /// false:
+ /// unsigned int f1(void);
+ /// void f2(void);
+ /// size_t f3(void);
+ /// \endcode
+ bool AlignFunctionDeclarations;
+ /// Only for ``AlignConsecutiveDeclarations``. Whether function pointers are
+ /// aligned.
+ /// \code
+ /// true:
+ /// unsigned i;
+ /// int &r;
+ /// int *p;
+ /// int (*f)();
+ ///
+ /// false:
+ /// unsigned i;
+ /// int &r;
+ /// int *p;
+ /// int (*f)();
+ /// \endcode
+ bool AlignFunctionPointers;
+ /// Only for ``AlignConsecutiveAssignments``. Whether short assignment
+ /// operators are left-padded to the same length as long ones in order to
+ /// put all assignment operators to the right of the left hand side.
+ /// \code
+ /// true:
+ /// a >>= 2;
+ /// bbb = 2;
+ ///
+ /// a = 2;
+ /// bbb >>= 2;
+ ///
+ /// false:
+ /// a >>= 2;
+ /// bbb = 2;
+ ///
+ /// a = 2;
+ /// bbb >>= 2;
+ /// \endcode
+ bool PadOperators;
+ bool operator==(const AlignConsecutiveStyle &R) const {
+ return Enabled == R.Enabled && AcrossEmptyLines == R.AcrossEmptyLines &&
+ AcrossComments == R.AcrossComments &&
+ AlignCompound == R.AlignCompound &&
+ AlignFunctionDeclarations == R.AlignFunctionDeclarations &&
+ AlignFunctionPointers == R.AlignFunctionPointers &&
+ PadOperators == R.PadOperators;
+ }
+ bool operator!=(const AlignConsecutiveStyle &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Style of aligning consecutive macro definitions.
+ ///
+ /// ``Consecutive`` will result in formattings like:
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ /// #define foo(x) (x * x)
+ /// #define bar(y, z) (y + z)
+ /// \endcode
+ /// \version 9
+ AlignConsecutiveStyle AlignConsecutiveMacros;
+ /// Style of aligning consecutive assignments.
+ ///
+ /// ``Consecutive`` will result in formattings like:
+ /// \code
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ /// \endcode
+ /// \version 3.8
+ AlignConsecutiveStyle AlignConsecutiveAssignments;
+ /// Style of aligning consecutive bit fields.
+ ///
+ /// ``Consecutive`` will align the bitfield separators of consecutive lines.
+ /// This will result in formattings like:
+ /// \code
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ /// \endcode
+ /// \version 11
+ AlignConsecutiveStyle AlignConsecutiveBitFields;
+ /// Style of aligning consecutive declarations.
+ ///
+ /// ``Consecutive`` will align the declaration names of consecutive lines.
+ /// This will result in formattings like:
+ /// \code
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ /// \endcode
+ /// \version 3.8
+ AlignConsecutiveStyle AlignConsecutiveDeclarations;
+
+ /// Alignment options.
+ ///
+ struct ShortCaseStatementsAlignmentStyle {
+ /// Whether aligning is enabled.
+ /// \code
+ /// true:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ /// default: return "";
+ /// }
+ ///
+ /// false:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ /// default: return "";
+ /// }
+ /// \endcode
+ bool Enabled;
+ /// Whether to align across empty lines.
+ /// \code
+ /// true:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ ///
+ /// default: return "";
+ /// }
+ ///
+ /// false:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ ///
+ /// default: return "";
+ /// }
+ /// \endcode
+ bool AcrossEmptyLines;
+ /// Whether to align across comments.
+ /// \code
+ /// true:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ /// /* A comment. */
+ /// default: return "";
+ /// }
+ ///
+ /// false:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ /// /* A comment. */
+ /// default: return "";
+ /// }
+ /// \endcode
+ bool AcrossComments;
+ /// Whether to align the case arrows when aligning short case expressions.
+ /// \code{.java}
+ /// true:
+ /// i = switch (day) {
+ /// case THURSDAY, SATURDAY -> 8;
+ /// case WEDNESDAY -> 9;
+ /// default -> 0;
+ /// };
+ ///
+ /// false:
+ /// i = switch (day) {
+ /// case THURSDAY, SATURDAY -> 8;
+ /// case WEDNESDAY -> 9;
+ /// default -> 0;
+ /// };
+ /// \endcode
+ bool AlignCaseArrows;
+ /// Whether aligned case labels are aligned on the colon, or on the tokens
+ /// after the colon.
+ /// \code
+ /// true:
+ /// switch (level) {
+ /// case log::info : return "info:";
+ /// case log::warning: return "warning:";
+ /// default : return "";
+ /// }
+ ///
+ /// false:
+ /// switch (level) {
+ /// case log::info: return "info:";
+ /// case log::warning: return "warning:";
+ /// default: return "";
+ /// }
+ /// \endcode
+ bool AlignCaseColons;
+ bool operator==(const ShortCaseStatementsAlignmentStyle &R) const {
+ return Enabled == R.Enabled && AcrossEmptyLines == R.AcrossEmptyLines &&
+ AcrossComments == R.AcrossComments &&
+ AlignCaseArrows == R.AlignCaseArrows &&
+ AlignCaseColons == R.AlignCaseColons;
+ }
+ };
+
+ /// Style of aligning consecutive short case labels.
+ /// Only applies if ``AllowShortCaseExpressionOnASingleLine`` or
+ /// ``AllowShortCaseLabelsOnASingleLine`` is ``true``.
+ ///
+ /// \code{.yaml}
+ /// # Example of usage:
+ /// AlignConsecutiveShortCaseStatements:
+ /// Enabled: true
+ /// AcrossEmptyLines: true
+ /// AcrossComments: true
+ /// AlignCaseColons: false
+ /// \endcode
+ /// \version 17
+ ShortCaseStatementsAlignmentStyle AlignConsecutiveShortCaseStatements;
+
+ /// Style of aligning consecutive TableGen DAGArg operator colons.
+ /// If enabled, align the colon inside DAGArg which have line break inside.
+ /// This works only when TableGenBreakInsideDAGArg is BreakElements or
+ /// BreakAll and the DAGArg is not excepted by
+ /// TableGenBreakingDAGArgOperators's effect.
+ /// \code
+ /// let dagarg = (ins
+ /// a :$src1,
+ /// aa :$src2,
+ /// aaa:$src3
+ /// )
+ /// \endcode
+ /// \version 19
+ AlignConsecutiveStyle AlignConsecutiveTableGenBreakingDAGArgColons;
+
+ /// Style of aligning consecutive TableGen cond operator colons.
+ /// Align the colons of cases inside !cond operators.
+ /// \code
+ /// !cond(!eq(size, 1) : 1,
+ /// !eq(size, 16): 1,
+ /// true : 0)
+ /// \endcode
+ /// \version 19
+ AlignConsecutiveStyle AlignConsecutiveTableGenCondOperatorColons;
+
+ /// Style of aligning consecutive TableGen definition colons.
+ /// This aligns the inheritance colons of consecutive definitions.
+ /// \code
+ /// def Def : Parent {}
+ /// def DefDef : Parent {}
+ /// def DefDefDef : Parent {}
+ /// \endcode
+ /// \version 19
+ AlignConsecutiveStyle AlignConsecutiveTableGenDefinitionColons;
+
+ /// Different styles for aligning escaped newlines.
+ enum EscapedNewlineAlignmentStyle : int8_t {
+ /// Don't align escaped newlines.
+ /// \code
+ /// #define A \
+ /// int aaaa; \
+ /// int b; \
+ /// int dddddddddd;
+ /// \endcode
+ ENAS_DontAlign,
+ /// Align escaped newlines as far left as possible.
+ /// \code
+ /// #define A \
+ /// int aaaa; \
+ /// int b; \
+ /// int dddddddddd;
+ /// \endcode
+ ENAS_Left,
+ /// Align escaped newlines as far left as possible, using the last line of
+ /// the preprocessor directive as the reference if it's the longest.
+ /// \code
+ /// #define A \
+ /// int aaaa; \
+ /// int b; \
+ /// int dddddddddd;
+ /// \endcode
+ ENAS_LeftWithLastLine,
+ /// Align escaped newlines in the right-most column.
+ /// \code
+ /// #define A \
+ /// int aaaa; \
+ /// int b; \
+ /// int dddddddddd;
+ /// \endcode
+ ENAS_Right,
+ };
+
+ /// Options for aligning backslashes in escaped newlines.
+ /// \version 5
+ EscapedNewlineAlignmentStyle AlignEscapedNewlines;
+
+ /// If ``true``, a space is inserted after the type of a compound literal.
+ /// \code
+ /// true: false:
+ /// (int) {1, 2, 3} vs. (int){1, 2, 3}
+ /// \endcode
+ /// \version 19
+ bool SpaceAfterCompoundLiteralType;
+
+ /// Different styles for aligning operands.
+ enum OperandAlignmentStyle : int8_t {
+ /// Do not align operands of binary and ternary expressions.
+ /// The wrapped lines are indented ``ContinuationIndentWidth`` spaces from
+ /// the start of the line.
+ OAS_DontAlign,
+ /// Horizontally align operands of binary and ternary expressions.
+ ///
+ /// Specifically, this aligns operands of a single expression that needs
+ /// to be split over multiple lines, e.g.:
+ /// \code
+ /// int aaa = bbbbbbbbbbbbbbb +
+ /// ccccccccccccccc;
+ /// \endcode
+ ///
+ /// When ``BreakBeforeBinaryOperators`` is set, the wrapped operator is
+ /// aligned with the operand on the first line.
+ /// \code
+ /// int aaa = bbbbbbbbbbbbbbb
+ /// + ccccccccccccccc;
+ /// \endcode
+ OAS_Align,
+ /// Horizontally align operands of binary and ternary expressions.
+ ///
+ /// This is similar to ``OAS_Align``, except when
+ /// ``BreakBeforeBinaryOperators`` is set, the operator is un-indented so
+ /// that the wrapped operand is aligned with the operand on the first line.
+ /// \code
+ /// int aaa = bbbbbbbbbbbbbbb
+ /// + ccccccccccccccc;
+ /// \endcode
+ OAS_AlignAfterOperator,
+ };
+
+ /// If ``true``, horizontally align operands of binary and ternary
+ /// expressions.
+ /// \version 3.5
+ OperandAlignmentStyle AlignOperands;
+
+ /// Enums for AlignTrailingComments
+ enum TrailingCommentsAlignmentKinds : int8_t {
+ /// Leave trailing comments as they are.
+ /// \code
+ /// int a; // comment
+ /// int ab; // comment
+ ///
+ /// int abc; // comment
+ /// int abcd; // comment
+ /// \endcode
+ TCAS_Leave,
+ /// Align trailing comments.
+ /// \code
+ /// int a; // comment
+ /// int ab; // comment
+ ///
+ /// int abc; // comment
+ /// int abcd; // comment
+ /// \endcode
+ TCAS_Always,
+ /// Don't align trailing comments but other formatter applies.
+ /// \code
+ /// int a; // comment
+ /// int ab; // comment
+ ///
+ /// int abc; // comment
+ /// int abcd; // comment
+ /// \endcode
+ TCAS_Never,
+ };
+
+ /// Alignment options
+ struct TrailingCommentsAlignmentStyle {
+ /// Specifies the way to align trailing comments.
+ TrailingCommentsAlignmentKinds Kind;
+ /// How many empty lines to apply alignment.
+ /// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+ /// it formats like below.
+ /// \code
+ /// int a; // all these
+ ///
+ /// int ab; // comments are
+ ///
+ ///
+ /// int abcdef; // aligned
+ /// \endcode
+ ///
+ /// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+ /// to 1, it formats like below.
+ /// \code
+ /// int a; // these are
+ ///
+ /// int ab; // aligned
+ ///
+ ///
+ /// int abcdef; // but this isn't
+ /// \endcode
+ unsigned OverEmptyLines;
+ /// If comments following preprocessor directive should be aligned with
+ /// comments that don't.
+ /// \code
+ /// true: false:
+ /// #define A // Comment vs. #define A // Comment
+ /// #define AB // Aligned #define AB // Aligned
+ /// int i; // Aligned int i; // Not aligned
+ /// \endcode
+ bool AlignPPAndNotPP;
+
+ bool operator==(const TrailingCommentsAlignmentStyle &R) const {
+ return Kind == R.Kind && OverEmptyLines == R.OverEmptyLines &&
+ AlignPPAndNotPP == R.AlignPPAndNotPP;
+ }
+ bool operator!=(const TrailingCommentsAlignmentStyle &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Control of trailing comments.
+ ///
+ /// The alignment stops at closing braces after a line break, and only
+ /// followed by other closing braces, a (``do-``) ``while``, a lambda call, or
+ /// a semicolon.
+ ///
+ /// \note
+ /// As of clang-format 16 this option is not a bool but can be set
+ /// to the options. Conventional bool options still can be parsed as before.
+ /// \endnote
+ ///
+ /// \code{.yaml}
+ /// # Example of usage:
+ /// AlignTrailingComments:
+ /// Kind: Always
+ /// OverEmptyLines: 2
+ /// \endcode
+ /// \version 3.7
+ TrailingCommentsAlignmentStyle AlignTrailingComments;
+
+ /// If a function call or braced initializer list doesn't fit on a line, allow
+ /// putting all arguments onto the next line, even if ``BinPackArguments`` is
+ /// ``false``.
+ /// \code
+ /// true:
+ /// callFunction(
+ /// a, b, c, d);
+ ///
+ /// false:
+ /// callFunction(a,
+ /// b,
+ /// c,
+ /// d);
+ /// \endcode
+ /// \version 9
+ bool AllowAllArgumentsOnNextLine;
+
+ /// This option is **deprecated**. See ``NextLine`` of
+ /// ``PackConstructorInitializers``.
+ /// \version 9
+ // bool AllowAllConstructorInitializersOnNextLine;
+
+ /// If the function declaration doesn't fit on a line,
+ /// allow putting all parameters of a function declaration onto
+ /// the next line even if ``BinPackParameters`` is ``OnePerLine``.
+ /// \code
+ /// true:
+ /// void myFunction(
+ /// int a, int b, int c, int d, int e);
+ ///
+ /// false:
+ /// void myFunction(int a,
+ /// int b,
+ /// int c,
+ /// int d,
+ /// int e);
+ /// \endcode
+ /// \version 3.3
+ bool AllowAllParametersOfDeclarationOnNextLine;
+
+ /// Different ways to break before a noexcept specifier.
+ enum BreakBeforeNoexceptSpecifierStyle : int8_t {
+ /// No line break allowed.
+ /// \code
+ /// void foo(int arg1,
+ /// double arg2) noexcept;
+ ///
+ /// void bar(int arg1, double arg2) noexcept(
+ /// noexcept(baz(arg1)) &&
+ /// noexcept(baz(arg2)));
+ /// \endcode
+ BBNSS_Never,
+ /// For a simple ``noexcept`` there is no line break allowed, but when we
+ /// have a condition it is.
+ /// \code
+ /// void foo(int arg1,
+ /// double arg2) noexcept;
+ ///
+ /// void bar(int arg1, double arg2)
+ /// noexcept(noexcept(baz(arg1)) &&
+ /// noexcept(baz(arg2)));
+ /// \endcode
+ BBNSS_OnlyWithParen,
+ /// Line breaks are allowed. But note that because of the associated
+ /// penalties ``clang-format`` often prefers not to break before the
+ /// ``noexcept``.
+ /// \code
+ /// void foo(int arg1,
+ /// double arg2) noexcept;
+ ///
+ /// void bar(int arg1, double arg2)
+ /// noexcept(noexcept(baz(arg1)) &&
+ /// noexcept(baz(arg2)));
+ /// \endcode
+ BBNSS_Always,
+ };
+
+ /// Controls if there could be a line break before a ``noexcept`` specifier.
+ /// \version 18
+ BreakBeforeNoexceptSpecifierStyle AllowBreakBeforeNoexceptSpecifier;
+
+ /// Allow breaking before ``Q_Property`` keywords ``READ``, ``WRITE``, etc. as
+ /// if they were preceded by a comma (``,``). This allows them to be formatted
+ /// according to ``BinPackParameters``.
+ /// \version 22
+ bool AllowBreakBeforeQtProperty;
+
+ /// Different styles for merging short blocks containing at most one
+ /// statement.
+ enum ShortBlockStyle : int8_t {
+ /// Never merge blocks into a single line.
+ /// \code
+ /// while (true) {
+ /// }
+ /// while (true) {
+ /// continue;
+ /// }
+ /// \endcode
+ SBS_Never,
+ /// Only merge empty blocks.
+ /// \code
+ /// while (true) {}
+ /// while (true) {
+ /// continue;
+ /// }
+ /// \endcode
+ SBS_Empty,
+ /// Always merge short blocks into a single line.
+ /// \code
+ /// while (true) {}
+ /// while (true) { continue; }
+ /// \endcode
+ SBS_Always,
+ };
+
+ /// Dependent on the value, ``while (true) { continue; }`` can be put on a
+ /// single line.
+ /// \version 3.5
+ ShortBlockStyle AllowShortBlocksOnASingleLine;
+
+ /// Whether to merge a short switch labeled rule into a single line.
+ /// \code{.java}
+ /// true: false:
+ /// switch (a) { vs. switch (a) {
+ /// case 1 -> 1; case 1 ->
+ /// default -> 0; 1;
+ /// }; default ->
+ /// 0;
+ /// };
+ /// \endcode
+ /// \version 19
+ bool AllowShortCaseExpressionOnASingleLine;
+
+ /// If ``true``, short case labels will be contracted to a single line.
+ /// \code
+ /// true: false:
+ /// switch (a) { vs. switch (a) {
+ /// case 1: x = 1; break; case 1:
+ /// case 2: return; x = 1;
+ /// } break;
+ /// case 2:
+ /// return;
+ /// }
+ /// \endcode
+ /// \version 3.6
+ bool AllowShortCaseLabelsOnASingleLine;
+
+ /// Allow short compound requirement on a single line.
+ /// \code
+ /// true:
+ /// template <typename T>
+ /// concept c = requires(T x) {
+ /// { x + 1 } -> std::same_as<int>;
+ /// };
+ ///
+ /// false:
+ /// template <typename T>
+ /// concept c = requires(T x) {
+ /// {
+ /// x + 1
+ /// } -> std::same_as<int>;
+ /// };
+ /// \endcode
+ /// \version 18
+ bool AllowShortCompoundRequirementOnASingleLine;
+
+ /// Allow short enums on a single line.
+ /// \code
+ /// true:
+ /// enum { A, B } myEnum;
+ ///
+ /// false:
+ /// enum {
+ /// A,
+ /// B
+ /// } myEnum;
+ /// \endcode
+ /// \version 11
+ bool AllowShortEnumsOnASingleLine;
+
+ /// Different styles for merging short functions containing at most one
+ /// statement.
+ ///
+ /// They can be read as a whole for compatibility. The choices are:
+ ///
+ /// * ``None``
+ /// Never merge functions into a single line.
+ ///
+ /// * ``InlineOnly``
+ /// Only merge functions defined inside a class. Same as ``inline``,
+ /// except it does not implies ``empty``: i.e. top level empty functions
+ /// are not merged either. This option is **deprecated** and is retained
+ /// for backwards compatibility. See ``Inline`` of ``ShortFunctionStyle``.
+ /// \code
+ /// class Foo {
+ /// void f() { foo(); }
+ /// };
+ /// void f() {
+ /// foo();
+ /// }
+ /// void f() {
+ /// }
+ /// \endcode
+ ///
+ /// * ``Empty``
+ /// Only merge empty functions. This option is **deprecated** and is
+ /// retained for backwards compatibility. See ``Empty`` of
+ /// ``ShortFunctionStyle``.
+ /// \code
+ /// void f() {}
+ /// void f2() {
+ /// bar2();
+ /// }
+ /// \endcode
+ ///
+ /// * ``Inline``
+ /// Only merge functions defined inside a class. Implies ``empty``. This
+ /// option is **deprecated** and is retained for backwards compatibility.
+ /// See ``Inline`` and ``Empty`` of ``ShortFunctionStyle``.
+ /// \code
+ /// class Foo {
+ /// void f() { foo(); }
+ /// };
+ /// void f() {
+ /// foo();
+ /// }
+ /// void f() {}
+ /// \endcode
+ ///
+ /// * ``All``
+ /// Merge all functions fitting on a single line.
+ /// \code
+ /// class Foo {
+ /// void f() { foo(); }
+ /// };
+ /// void f() { bar(); }
+ /// \endcode
+ ///
+ /// Also can be specified as a nested configuration flag:
+ /// \code
+ /// # Example of usage:
+ /// AllowShortFunctionsOnASingleLine: InlineOnly
+ ///
+ /// # or more granular control:
+ /// AllowShortFunctionsOnASingleLine:
+ /// Empty: false
+ /// Inline: true
+ /// Other: false
+ /// \endcode
+ struct ShortFunctionStyle {
+ /// Merge top-level empty functions.
+ /// \code
+ /// void f() {}
+ /// void f2() {
+ /// bar2();
+ /// }
+ /// void f3() { /* comment */ }
+ /// \endcode
+ bool Empty;
+ /// Merge functions defined inside a class.
+ /// \code
+ /// class Foo {
+ /// void f() { foo(); }
+ /// void g() {}
+ /// };
+ /// void f() {
+ /// foo();
+ /// }
+ /// void f() {
+ /// }
+ /// \endcode
+ bool Inline;
+ /// Merge all functions fitting on a single line. Please note that this
+ /// control does not include Empty
+ /// \code
+ /// class Foo {
+ /// void f() { foo(); }
+ /// };
+ /// void f() { bar(); }
+ /// \endcode
+ bool Other;
+
+ bool operator==(const ShortFunctionStyle &R) const {
+ return Empty == R.Empty && Inline == R.Inline && Other == R.Other;
+ }
+ bool operator!=(const ShortFunctionStyle &R) const { return !(*this == R); }
+ ShortFunctionStyle() : Empty(false), Inline(false), Other(false) {}
+ ShortFunctionStyle(bool Empty, bool Inline, bool Other)
+ : Empty(Empty), Inline(Inline), Other(Other) {}
+ bool isAll() const { return Empty && Inline && Other; }
+ static ShortFunctionStyle setEmptyOnly() {
+ return ShortFunctionStyle(true, false, false);
+ }
+ static ShortFunctionStyle setEmptyAndInline() {
+ return ShortFunctionStyle(true, true, false);
+ }
+ static ShortFunctionStyle setInlineOnly() {
+ return ShortFunctionStyle(false, true, false);
+ }
+ static ShortFunctionStyle setAll() {
+ return ShortFunctionStyle(true, true, true);
+ }
+ };
+
+ /// Dependent on the value, ``int f() { return 0; }`` can be put on a
+ /// single line.
+ /// \version 3.5
+ ShortFunctionStyle AllowShortFunctionsOnASingleLine;
+
+ /// Different styles for handling short if statements.
+ enum ShortIfStyle : int8_t {
+ /// Never put short ifs on the same line.
+ /// \code
+ /// if (a)
+ /// return;
+ ///
+ /// if (b)
+ /// return;
+ /// else
+ /// return;
+ ///
+ /// if (c)
+ /// return;
+ /// else {
+ /// return;
+ /// }
+ /// \endcode
+ SIS_Never,
+ /// Put short ifs on the same line only if there is no else statement.
+ /// \code
+ /// if (a) return;
+ ///
+ /// if (b)
+ /// return;
+ /// else
+ /// return;
+ ///
+ /// if (c)
+ /// return;
+ /// else {
+ /// return;
+ /// }
+ /// \endcode
+ SIS_WithoutElse,
+ /// Put short ifs, but not else ifs nor else statements, on the same line.
+ /// \code
+ /// if (a) return;
+ ///
+ /// if (b) return;
+ /// else if (b)
+ /// return;
+ /// else
+ /// return;
+ ///
+ /// if (c) return;
+ /// else {
+ /// return;
+ /// }
+ /// \endcode
+ SIS_OnlyFirstIf,
+ /// Always put short ifs, else ifs and else statements on the same
+ /// line.
+ /// \code
+ /// if (a) return;
+ ///
+ /// if (b) return;
+ /// else return;
+ ///
+ /// if (c) return;
+ /// else {
+ /// return;
+ /// }
+ /// \endcode
+ SIS_AllIfsAndElse,
+ };
+
+ /// Dependent on the value, ``if (a) return;`` can be put on a single line.
+ /// \version 3.3
+ ShortIfStyle AllowShortIfStatementsOnASingleLine;
+
+ /// Different styles for merging short lambdas containing at most one
+ /// statement.
+ enum ShortLambdaStyle : int8_t {
+ /// Never merge lambdas into a single line.
+ SLS_None,
+ /// Only merge empty lambdas.
+ /// \code
+ /// auto lambda = [](int a) {};
+ /// auto lambda2 = [](int a) {
+ /// return a;
+ /// };
+ /// \endcode
+ SLS_Empty,
+ /// Merge lambda into a single line if the lambda is argument of a function.
+ /// \code
+ /// auto lambda = [](int x, int y) {
+ /// return x < y;
+ /// };
+ /// sort(a.begin(), a.end(), [](int x, int y) { return x < y; });
+ /// \endcode
+ SLS_Inline,
+ /// Merge all lambdas fitting on a single line.
+ /// \code
+ /// auto lambda = [](int a) {};
+ /// auto lambda2 = [](int a) { return a; };
+ /// \endcode
+ SLS_All,
+ };
+
+ /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
+ /// single line.
+ /// \version 9
+ ShortLambdaStyle AllowShortLambdasOnASingleLine;
+
+ /// If ``true``, ``while (true) continue;`` can be put on a single
+ /// line.
+ /// \version 3.7
+ bool AllowShortLoopsOnASingleLine;
+
+ /// If ``true``, ``namespace a { class b; }`` can be put on a single line.
+ /// \version 20
+ bool AllowShortNamespacesOnASingleLine;
+
+ /// Different styles for merging short records (``class``,``struct``, and
+ /// ``union``).
+ enum ShortRecordStyle : int8_t {
+ /// Never merge records into a single line.
+ SRS_Never,
+ /// Only merge empty records if the opening brace was not wrapped,
+ /// i.e. the corresponding ``BraceWrapping.After...`` option was not set.
+ SRS_EmptyAndAttached,
+ /// Only merge empty records.
+ /// \code
+ /// struct foo {};
+ /// struct bar
+ /// {
+ /// int i;
+ /// };
+ /// \endcode
+ SRS_Empty,
+ /// Merge all records that fit on a single line.
+ /// \code
+ /// struct foo {};
+ /// struct bar { int i; };
+ /// \endcode
+ SRS_Always
+ };
+
+ /// Dependent on the value, ``struct bar { int i; };`` can be put on a single
+ /// line.
+ /// \version 23
+ ShortRecordStyle AllowShortRecordOnASingleLine;
+
+ /// Different ways to break after the function definition return type.
+ /// This option is **deprecated** and is retained for backwards compatibility.
+ enum DefinitionReturnTypeBreakingStyle : int8_t {
+ /// Break after return type automatically.
+ /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
+ DRTBS_None,
+ /// Always break after the return type.
+ DRTBS_All,
+ /// Always break after the return types of top-level functions.
+ DRTBS_TopLevel,
+ };
+
+ /// Different ways to break after the function definition or
+ /// declaration return type.
+ enum ReturnTypeBreakingStyle : int8_t {
+ /// This is **deprecated**. See ``Automatic`` below.
+ RTBS_None,
+ /// Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
+ /// \code
+ /// class A {
+ /// int f() { return 0; };
+ /// };
+ /// int f();
+ /// int f() { return 1; }
+ /// int
+ /// LongName::AnotherLongName();
+ /// \endcode
+ RTBS_Automatic,
+ /// Same as ``Automatic`` above, except that there is no break after short
+ /// return types.
+ /// \code
+ /// class A {
+ /// int f() { return 0; };
+ /// };
+ /// int f();
+ /// int f() { return 1; }
+ /// int LongName::
+ /// AnotherLongName();
+ /// \endcode
+ RTBS_ExceptShortType,
+ /// Always break after the return type.
+ /// \code
+ /// class A {
+ /// int
+ /// f() {
+ /// return 0;
+ /// };
+ /// };
+ /// int
+ /// f();
+ /// int
+ /// f() {
+ /// return 1;
+ /// }
+ /// int
+ /// LongName::AnotherLongName();
+ /// \endcode
+ RTBS_All,
+ /// Always break after the return types of top-level functions.
+ /// \code
+ /// class A {
+ /// int f() { return 0; };
+ /// };
+ /// int
+ /// f();
+ /// int
+ /// f() {
+ /// return 1;
+ /// }
+ /// int
+ /// LongName::AnotherLongName();
+ /// \endcode
+ RTBS_TopLevel,
+ /// Always break after the return type of function definitions.
+ /// \code
+ /// class A {
+ /// int
+ /// f() {
+ /// return 0;
+ /// };
+ /// };
+ /// int f();
+ /// int
+ /// f() {
+ /// return 1;
+ /// }
+ /// int
+ /// LongName::AnotherLongName();
+ /// \endcode
+ RTBS_AllDefinitions,
+ /// Always break after the return type of top-level definitions.
+ /// \code
+ /// class A {
+ /// int f() { return 0; };
+ /// };
+ /// int f();
+ /// int
+ /// f() {
+ /// return 1;
+ /// }
+ /// int
+ /// LongName::AnotherLongName();
+ /// \endcode
+ RTBS_TopLevelDefinitions,
+ };
+
+ /// The function definition return type breaking style to use. This
+ /// option is **deprecated** and is retained for backwards compatibility.
+ /// \version 3.7
+ DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
+
+ /// This option is renamed to ``BreakAfterReturnType``.
+ /// \version 3.8
+ /// @deprecated
+ // ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
+
+ /// If ``true``, always break before multiline string literals.
+ ///
+ /// This flag is mean to make cases where there are multiple multiline strings
+ /// in a file look more consistent. Thus, it will only take effect if wrapping
+ /// the string at that point leads to it being indented
+ /// ``ContinuationIndentWidth`` spaces from the start of the line.
+ /// \code
+ /// true: false:
+ /// aaaa = vs. aaaa = "bbbb"
+ /// "bbbb" "cccc";
+ /// "cccc";
+ /// \endcode
+ /// \version 3.4
+ bool AlwaysBreakBeforeMultilineStrings;
+
+ /// Different ways to break after the template declaration.
+ enum BreakTemplateDeclarationsStyle : int8_t {
+ /// Do not change the line breaking before the declaration.
+ /// \code
+ /// template <typename T>
+ /// T foo() {
+ /// }
+ /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
+ /// int bbbbbbbbbbbbbbbbbbbbb) {
+ /// }
+ /// \endcode
+ BTDS_Leave,
+ /// Do not force break before declaration.
+ /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
+ /// \code
+ /// template <typename T> T foo() {
+ /// }
+ /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
+ /// int bbbbbbbbbbbbbbbbbbbbb) {
+ /// }
+ /// \endcode
+ BTDS_No,
+ /// Force break after template declaration only when the following
+ /// declaration spans multiple lines.
+ /// \code
+ /// template <typename T> T foo() {
+ /// }
+ /// template <typename T>
+ /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
+ /// int bbbbbbbbbbbbbbbbbbbbb) {
+ /// }
+ /// \endcode
+ BTDS_MultiLine,
+ /// Always break after template declaration.
+ /// \code
+ /// template <typename T>
+ /// T foo() {
+ /// }
+ /// template <typename T>
+ /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
+ /// int bbbbbbbbbbbbbbbbbbbbb) {
+ /// }
+ /// \endcode
+ BTDS_Yes
+ };
+
+ /// This option is renamed to ``BreakTemplateDeclarations``.
+ /// \version 3.4
+ /// @deprecated
+ // BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
+
+ /// A vector of strings that should be interpreted as attributes/qualifiers
+ /// instead of identifiers. This can be useful for language extensions or
+ /// static analyzer annotations.
+ ///
+ /// For example:
+ /// \code
+ /// x = (char *__capability)&y;
+ /// int function(void) __unused;
+ /// void only_writes_to_buffer(char *__output buffer);
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// AttributeMacros: [__capability, __output, __unused]
+ /// \endcode
+ ///
+ /// \version 12
+ std::vector<std::string> AttributeMacros;
+
+ /// If ``false``, a function call's arguments will either be all on the
+ /// same line or will have one line each.
+ /// \code
+ /// true:
+ /// void f() {
+ /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
+ /// }
+ ///
+ /// false:
+ /// void f() {
+ /// f(aaaaaaaaaaaaaaaaaaaa,
+ /// aaaaaaaaaaaaaaaaaaaa,
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
+ /// }
+ /// \endcode
+ /// \version 3.7
+ bool BinPackArguments;
+
+ /// If ``BinPackLongBracedList`` is ``true`` it overrides
+ /// ``BinPackArguments`` if there are 20 or more items in a braced
+ /// initializer list.
+ /// \code
+ /// BinPackLongBracedList: false vs. BinPackLongBracedList: true
+ /// vector<int> x{ vector<int> x{1, 2, ...,
+ /// 20, 21};
+ /// 1,
+ /// 2,
+ /// ...,
+ /// 20,
+ /// 21};
+ /// \endcode
+ /// \version 21
+ bool BinPackLongBracedList;
+
+ /// Different way to try to fit all parameters on a line.
+ enum BinPackParametersStyle : int8_t {
+ /// Bin-pack parameters.
+ /// \code
+ /// void f(int a, int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
+ /// int ccccccccccccccccccccccccccccccccccccccccccc);
+ /// \endcode
+ BPPS_BinPack,
+ /// Put all parameters on the current line if they fit.
+ /// Otherwise, put each one on its own line.
+ /// \code
+ /// void f(int a, int b, int c);
+ ///
+ /// void f(int a,
+ /// int b,
+ /// int ccccccccccccccccccccccccccccccccccccc);
+ /// \endcode
+ BPPS_OnePerLine,
+ /// Always put each parameter on its own line.
+ /// \code
+ /// void f(int a,
+ /// int b,
+ /// int c);
+ /// \endcode
+ BPPS_AlwaysOnePerLine,
+ };
+
+ /// The bin pack parameters style to use.
+ /// \version 3.7
+ BinPackParametersStyle BinPackParameters;
+
+ /// Styles for adding spacing around ``:`` in bitfield definitions.
+ enum BitFieldColonSpacingStyle : int8_t {
+ /// Add one space on each side of the ``:``
+ /// \code
+ /// unsigned bf : 2;
+ /// \endcode
+ BFCS_Both,
+ /// Add no space around the ``:`` (except when needed for
+ /// ``AlignConsecutiveBitFields``).
+ /// \code
+ /// unsigned bf:2;
+ /// \endcode
+ BFCS_None,
+ /// Add space before the ``:`` only
+ /// \code
+ /// unsigned bf :2;
+ /// \endcode
+ BFCS_Before,
+ /// Add space after the ``:`` only (space may be added before if
+ /// needed for ``AlignConsecutiveBitFields``).
+ /// \code
+ /// unsigned bf: 2;
+ /// \endcode
+ BFCS_After
+ };
+ /// The BitFieldColonSpacingStyle to use for bitfields.
+ /// \version 12
+ BitFieldColonSpacingStyle BitFieldColonSpacing;
+
+ /// The number of columns to use to indent the contents of braced init lists.
+ /// If unset or negative, ``ContinuationIndentWidth`` is used.
+ /// \code
+ /// AlignAfterOpenBracket: AlwaysBreak
+ /// BracedInitializerIndentWidth: 2
+ ///
+ /// void f() {
+ /// SomeClass c{
+ /// "foo",
+ /// "bar",
+ /// "baz",
+ /// };
+ /// auto s = SomeStruct{
+ /// .foo = "foo",
+ /// .bar = "bar",
+ /// .baz = "baz",
+ /// };
+ /// SomeArrayT a[3] = {
+ /// {
+ /// foo,
+ /// bar,
+ /// },
+ /// {
+ /// foo,
+ /// bar,
+ /// },
+ /// SomeArrayT{},
+ /// };
+ /// }
+ /// \endcode
+ /// \version 17
+ int BracedInitializerIndentWidth;
+
+ /// Different ways to wrap braces after control statements.
+ enum BraceWrappingAfterControlStatementStyle : int8_t {
+ /// Never wrap braces after a control statement.
+ /// \code
+ /// if (foo()) {
+ /// } else {
+ /// }
+ /// for (int i = 0; i < 10; ++i) {
+ /// }
+ /// \endcode
+ BWACS_Never,
+ /// Only wrap braces after a multi-line control statement.
+ /// \code
+ /// if (foo && bar &&
+ /// baz)
+ /// {
+ /// quux();
+ /// }
+ /// while (foo || bar) {
+ /// }
+ /// \endcode
+ BWACS_MultiLine,
+ /// Always wrap braces after a control statement.
+ /// \code
+ /// if (foo())
+ /// {
+ /// } else
+ /// {}
+ /// for (int i = 0; i < 10; ++i)
+ /// {}
+ /// \endcode
+ BWACS_Always
+ };
+
+ /// Precise control over the wrapping of braces.
+ /// \code
+ /// # Should be declared this way:
+ /// BreakBeforeBraces: Custom
+ /// BraceWrapping:
+ /// AfterClass: true
+ /// \endcode
+ struct BraceWrappingFlags {
+ /// Wrap case labels.
+ /// \code
+ /// false: true:
+ /// switch (foo) { vs. switch (foo) {
+ /// case 1: { case 1:
+ /// bar(); {
+ /// break; bar();
+ /// } break;
+ /// default: { }
+ /// plop(); default:
+ /// } {
+ /// } plop();
+ /// }
+ /// }
+ /// \endcode
+ bool AfterCaseLabel;
+ /// Wrap class definitions.
+ /// \code
+ /// true:
+ /// class foo
+ /// {};
+ ///
+ /// false:
+ /// class foo {};
+ /// \endcode
+ bool AfterClass;
+
+ /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
+ BraceWrappingAfterControlStatementStyle AfterControlStatement;
+ /// Wrap enum definitions.
+ /// \code
+ /// true:
+ /// enum X : int
+ /// {
+ /// B
+ /// };
+ ///
+ /// false:
+ /// enum X : int { B };
+ /// \endcode
+ bool AfterEnum;
+ /// Wrap function definitions.
+ /// \code
+ /// true:
+ /// void foo()
+ /// {
+ /// bar();
+ /// bar2();
+ /// }
+ ///
+ /// false:
+ /// void foo() {
+ /// bar();
+ /// bar2();
+ /// }
+ /// \endcode
+ bool AfterFunction;
+ /// Wrap namespace definitions.
+ /// \code
+ /// true:
+ /// namespace
+ /// {
+ /// int foo();
+ /// int bar();
+ /// }
+ ///
+ /// false:
+ /// namespace {
+ /// int foo();
+ /// int bar();
+ /// }
+ /// \endcode
+ bool AfterNamespace;
+ /// Wrap ObjC definitions (interfaces, implementations...).
+ /// \note
+ /// @autoreleasepool and @synchronized blocks are wrapped
+ /// according to ``AfterControlStatement`` flag.
+ /// \endnote
+ bool AfterObjCDeclaration;
+ /// Wrap struct definitions.
+ /// \code
+ /// true:
+ /// struct foo
+ /// {
+ /// int x;
+ /// };
+ ///
+ /// false:
+ /// struct foo {
+ /// int x;
+ /// };
+ /// \endcode
+ bool AfterStruct;
+ /// Wrap union definitions.
+ /// \code
+ /// true:
+ /// union foo
+ /// {
+ /// int x;
+ /// }
+ ///
+ /// false:
+ /// union foo {
+ /// int x;
+ /// }
+ /// \endcode
+ bool AfterUnion;
+ /// Wrap extern blocks.
+ /// \code
+ /// true:
+ /// extern "C"
+ /// {
+ /// int foo();
+ /// }
+ ///
+ /// false:
+ /// extern "C" {
+ /// int foo();
+ /// }
+ /// \endcode
+ bool AfterExternBlock; // Partially superseded by IndentExternBlock
+ /// Wrap before ``catch``.
+ /// \code
+ /// true:
+ /// try {
+ /// foo();
+ /// }
+ /// catch () {
+ /// }
+ ///
+ /// false:
+ /// try {
+ /// foo();
+ /// } catch () {
+ /// }
+ /// \endcode
+ bool BeforeCatch;
+ /// Wrap before ``else``.
+ /// \code
+ /// true:
+ /// if (foo()) {
+ /// }
+ /// else {
+ /// }
+ ///
+ /// false:
+ /// if (foo()) {
+ /// } else {
+ /// }
+ /// \endcode
+ bool BeforeElse;
+ /// Wrap lambda block.
+ /// \code
+ /// true:
+ /// connect(
+ /// []()
+ /// {
+ /// foo();
+ /// bar();
+ /// });
+ ///
+ /// false:
+ /// connect([]() {
+ /// foo();
+ /// bar();
+ /// });
+ /// \endcode
+ bool BeforeLambdaBody;
+ /// Wrap before ``while``.
+ /// \code
+ /// true:
+ /// do {
+ /// foo();
+ /// }
+ /// while (1);
+ ///
+ /// false:
+ /// do {
+ /// foo();
+ /// } while (1);
+ /// \endcode
+ bool BeforeWhile;
+ /// Indent the wrapped braces themselves.
+ bool IndentBraces;
+ /// If ``false``, empty function body can be put on a single line.
+ /// This option is used only if the opening brace of the function has
+ /// already been wrapped, i.e. the ``AfterFunction`` brace wrapping mode is
+ /// set, and the function could/should not be put on a single line (as per
+ /// ``AllowShortFunctionsOnASingleLine`` and constructor formatting
+ /// options).
+ /// \code
+ /// false: true:
+ /// int f() vs. int f()
+ /// {} {
+ /// }
+ /// \endcode
+ ///
+ bool SplitEmptyFunction;
+ /// If ``false``, empty record (e.g. class, struct or union) body
+ /// can be put on a single line. This option is used only if the opening
+ /// brace of the record has already been wrapped, i.e. the ``AfterClass``
+ /// (for classes) brace wrapping mode is set.
+ /// \code
+ /// false: true:
+ /// class Foo vs. class Foo
+ /// {} {
+ /// }
+ /// \endcode
+ ///
+ bool SplitEmptyRecord;
+ /// If ``false``, empty namespace body can be put on a single line.
+ /// This option is used only if the opening brace of the namespace has
+ /// already been wrapped, i.e. the ``AfterNamespace`` brace wrapping mode is
+ /// set.
+ /// \code
+ /// false: true:
+ /// namespace Foo vs. namespace Foo
+ /// {} {
+ /// }
+ /// \endcode
+ ///
+ bool SplitEmptyNamespace;
+ };
+
+ /// Control of individual brace wrapping cases.
+ ///
+ /// If ``BreakBeforeBraces`` is set to ``Custom``, use this to specify how
+ /// each individual brace case should be handled. Otherwise, this is ignored.
+ /// \code{.yaml}
+ /// # Example of usage:
+ /// BreakBeforeBraces: Custom
+ /// BraceWrapping:
+ /// AfterEnum: true
+ /// AfterStruct: false
+ /// SplitEmptyFunction: false
+ /// \endcode
+ /// \version 3.8
+ BraceWrappingFlags BraceWrapping;
+
+ /// Break between adjacent string literals.
+ /// \code
+ /// true:
+ /// return "Code"
+ /// "\0\52\26\55\55\0"
+ /// "x013"
+ /// "\02\xBA";
+ /// false:
+ /// return "Code" "\0\52\26\55\55\0" "x013" "\02\xBA";
+ /// \endcode
+ /// \version 18
+ bool BreakAdjacentStringLiterals;
+
+ /// Different ways to break after the last attribute of a group before a
+ /// declaration or control statement.
+ enum AttributeBreakingStyle : int8_t {
+ /// Always break after the last attribute of the group.
+ /// \code
+ /// [[maybe_unused]]
+ /// const int i;
+ /// [[gnu::const]] [[maybe_unused]]
+ /// int j;
+ ///
+ /// [[nodiscard]]
+ /// inline int f();
+ /// [[gnu::const]] [[nodiscard]]
+ /// int g();
+ ///
+ /// [[likely]]
+ /// if (a)
+ /// f();
+ /// else
+ /// g();
+ ///
+ /// switch (b) {
+ /// [[unlikely]]
+ /// case 1:
+ /// ++b;
+ /// break;
+ /// [[likely]]
+ /// default:
+ /// return;
+ /// }
+ /// \endcode
+ ABS_Always,
+ /// Leave the line breaking after the last attribute of the group as is.
+ /// \code
+ /// [[maybe_unused]] const int i;
+ /// [[gnu::const]] [[maybe_unused]]
+ /// int j;
+ ///
+ /// [[nodiscard]] inline int f();
+ /// [[gnu::const]] [[nodiscard]]
+ /// int g();
+ ///
+ /// [[likely]] if (a)
+ /// f();
+ /// else
+ /// g();
+ ///
+ /// switch (b) {
+ /// [[unlikely]] case 1:
+ /// ++b;
+ /// break;
+ /// [[likely]]
+ /// default:
+ /// return;
+ /// }
+ /// \endcode
+ ABS_Leave,
+ /// Same as ``Leave`` except that it applies to all attributes of the group.
+ /// \code
+ /// [[deprecated("Don't use this version")]]
+ /// [[nodiscard]]
+ /// bool foo() {
+ /// return true;
+ /// }
+ ///
+ /// [[deprecated("Don't use this version")]]
+ /// [[nodiscard]] bool bar() {
+ /// return true;
+ /// }
+ /// \endcode
+ ABS_LeaveAll,
+ /// Never break after the last attribute of the group.
+ /// \code
+ /// [[maybe_unused]] const int i;
+ /// [[gnu::const]] [[maybe_unused]] int j;
+ ///
+ /// [[nodiscard]] inline int f();
+ /// [[gnu::const]] [[nodiscard]] int g();
+ ///
+ /// [[likely]] if (a)
+ /// f();
+ /// else
+ /// g();
+ ///
+ /// switch (b) {
+ /// [[unlikely]] case 1:
+ /// ++b;
+ /// break;
+ /// [[likely]] default:
+ /// return;
+ /// }
+ /// \endcode
+ ABS_Never,
+ };
+
+ /// Break after a group of C++11 attributes before variable or function
+ /// (including constructor/destructor) declaration/definition names or before
+ /// control statements, i.e. ``if``, ``switch`` (including ``case`` and
+ /// ``default`` labels), ``for``, and ``while`` statements.
+ /// \version 16
+ AttributeBreakingStyle BreakAfterAttributes;
+
+ /// Force break after the left bracket of a braced initializer list (when
+ /// ``Cpp11BracedListStyle`` is ``true``) when the list exceeds the column
+ /// limit.
+ /// \code
+ /// true: false:
+ /// vector<int> x { vs. vector<int> x {1,
+ /// 1, 2, 3} 2, 3}
+ /// \endcode
+ /// \version 22
+ bool BreakAfterOpenBracketBracedList;
+
+ /// Force break after the left parenthesis of a function (declaration,
+ /// definition, call) when the parameters exceed the column limit.
+ /// \code
+ /// true: false:
+ /// foo ( vs. foo (a,
+ /// a , b) b)
+ /// \endcode
+ /// \version 22
+ bool BreakAfterOpenBracketFunction;
+
+ /// Force break after the left parenthesis of an if control statement
+ /// when the expression exceeds the column limit.
+ /// \code
+ /// true: false:
+ /// if constexpr ( vs. if constexpr (a ||
+ /// a || b) b)
+ /// \endcode
+ /// \version 22
+ bool BreakAfterOpenBracketIf;
+
+ /// Force break after the left parenthesis of a loop control statement
+ /// when the expression exceeds the column limit.
+ /// \code
+ /// true: false:
+ /// while ( vs. while (a &&
+ /// a && b) { b) {
+ /// \endcode
+ /// \version 22
+ bool BreakAfterOpenBracketLoop;
+
+ /// Force break after the left parenthesis of a switch control statement
+ /// when the expression exceeds the column limit.
+ /// \code
+ /// true: false:
+ /// switch ( vs. switch (a +
+ /// a + b) { b) {
+ /// \endcode
+ /// \version 22
+ bool BreakAfterOpenBracketSwitch;
+
+ /// The function declaration return type breaking style to use.
+ /// \version 19
+ ReturnTypeBreakingStyle BreakAfterReturnType;
+
+ /// If ``true``, clang-format will always break after a Json array ``[``
+ /// otherwise it will scan until the closing ``]`` to determine if it should
+ /// add newlines between elements (prettier compatible).
+ ///
+ /// \note
+ /// This is currently only for formatting JSON.
+ /// \endnote
+ /// \code
+ /// true: false:
+ /// [ vs. [1, 2, 3, 4]
+ /// 1,
+ /// 2,
+ /// 3,
+ /// 4
+ /// ]
+ /// \endcode
+ /// \version 16
+ bool BreakArrays;
+
+ /// The style of wrapping parameters on the same line (bin-packed) or
+ /// on one line each.
+ enum BinPackStyle : int8_t {
+ /// Automatically determine parameter bin-packing behavior.
+ BPS_Auto,
+ /// Always bin-pack parameters.
+ BPS_Always,
+ /// Never bin-pack parameters.
+ BPS_Never,
+ };
+
+ /// The style of breaking before or after binary operators.
+ enum BinaryOperatorStyle : int8_t {
+ /// Break after operators.
+ /// \code
+ /// LooooooooooongType loooooooooooooooooooooongVariable =
+ /// someLooooooooooooooooongFunction();
+ ///
+ /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
+ /// ccccccccccccccccccccccccccccccccccccccccc;
+ /// \endcode
+ BOS_None,
+ /// Break before operators that aren't assignments.
+ /// \code
+ /// LooooooooooongType loooooooooooooooooooooongVariable =
+ /// someLooooooooooooooooongFunction();
+ ///
+ /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// > ccccccccccccccccccccccccccccccccccccccccc;
+ /// \endcode
+ BOS_NonAssignment,
+ /// Break before operators.
+ /// \code
+ /// LooooooooooongType loooooooooooooooooooooongVariable
+ /// = someLooooooooooooooooongFunction();
+ ///
+ /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ /// > ccccccccccccccccccccccccccccccccccccccccc;
+ /// \endcode
+ BOS_All,
+ };
+
+ /// The way to wrap binary operators.
+ /// \version 3.6
+ BinaryOperatorStyle BreakBeforeBinaryOperators;
+
+ /// Different ways to attach braces to their surrounding context.
+ enum BraceBreakingStyle : int8_t {
+ /// Always attach braces to surrounding context.
+ /// \code
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i) {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b) {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Attach,
+ /// Like ``Attach``, but break before braces on function, namespace and
+ /// class definitions.
+ /// \code
+ /// namespace N
+ /// {
+ /// enum E {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Linux,
+ /// Like ``Attach``, but break before braces on enum, function, and record
+ /// definitions.
+ /// \code
+ /// namespace N {
+ /// enum E
+ /// {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Mozilla,
+ /// Like ``Attach``, but break before function definitions, ``catch``, and
+ /// ``else``.
+ /// \code
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// }
+ /// else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Stroustrup,
+ /// Always break before braces.
+ /// \code
+ /// namespace N
+ /// {
+ /// enum E
+ /// {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Allman,
+ /// Like ``Allman`` but always indent braces and line up code with braces.
+ /// \code
+ /// namespace N
+ /// {
+ /// enum E
+ /// {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_Whitesmiths,
+ /// Always break before braces and add an extra level of indentation to
+ /// braces of control statements, not to those of class, function
+ /// or other definitions.
+ /// \code
+ /// namespace N
+ /// {
+ /// enum E
+ /// {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// }
+ /// while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_GNU,
+ /// Like ``Attach``, but break before functions.
+ /// \code
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
+ /// \endcode
+ BS_WebKit,
+ /// Configure each individual brace in ``BraceWrapping``.
+ BS_Custom
+ };
+
+ /// The brace breaking style to use.
+ /// \version 3.7
+ BraceBreakingStyle BreakBeforeBraces;
+
+ /// Force break before the right bracket of a braced initializer list (when
+ /// ``Cpp11BracedListStyle`` is ``true``) when the list exceeds the column
+ /// limit. The break before the right bracket is only made if there is a
+ /// break after the opening bracket.
+ /// \code
+ /// true: false:
+ /// vector<int> x { vs. vector<int> x {
+ /// 1, 2, 3 1, 2, 3}
+ /// }
+ /// \endcode
+ /// \version 22
+ bool BreakBeforeCloseBracketBracedList;
+
+ /// Force break before the right parenthesis of a function (declaration,
+ /// definition, call) when the parameters exceed the column limit.
+ /// \code
+ /// true: false:
+ /// foo ( vs. foo (
+ /// a , b a , b)
+ /// )
+ /// \endcode
+ /// \version 22
+ bool BreakBeforeCloseBracketFunction;
+
+ /// Force break before the right parenthesis of an if control statement
+ /// when the expression exceeds the column limit. The break before the
+ /// closing parenthesis is only made if there is a break after the opening
+ /// parenthesis.
+ /// \code
+ /// true: false:
+ /// if constexpr ( vs. if constexpr (
+ /// a || b a || b )
+ /// )
+ /// \endcode
+ /// \version 22
+ bool BreakBeforeCloseBracketIf;
+
+ /// Force break before the right parenthesis of a loop control statement
+ /// when the expression exceeds the column limit. The break before the
+ /// closing parenthesis is only made if there is a break after the opening
+ /// parenthesis.
+ /// \code
+ /// true: false:
+ /// while ( vs. while (
+ /// a && b a && b) {
+ /// ) {
+ /// \endcode
+ /// \version 22
+ bool BreakBeforeCloseBracketLoop;
+
+ /// Force break before the right parenthesis of a switch control statement
+ /// when the expression exceeds the column limit. The break before the
+ /// closing parenthesis is only made if there is a break after the opening
+ /// parenthesis.
+ /// \code
+ /// true: false:
+ /// switch ( vs. switch (
+ /// a + b a + b) {
+ /// ) {
+ /// \endcode
+ /// \version 22
+ bool BreakBeforeCloseBracketSwitch;
+
+ /// Different ways to break before concept declarations.
+ enum BreakBeforeConceptDeclarationsStyle : int8_t {
+ /// Keep the template declaration line together with ``concept``.
+ /// \code
+ /// template <typename T> concept C = ...;
+ /// \endcode
+ BBCDS_Never,
+ /// Breaking between template declaration and ``concept`` is allowed. The
+ /// actual behavior depends on the content and line breaking rules and
+ /// penalties.
+ BBCDS_Allowed,
+ /// Always break before ``concept``, putting it in the line after the
+ /// template declaration.
+ /// \code
+ /// template <typename T>
+ /// concept C = ...;
+ /// \endcode
+ BBCDS_Always,
+ };
+
+ /// The concept declaration style to use.
+ /// \version 12
+ BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations;
+
+ /// Different ways to break ASM parameters.
+ enum BreakBeforeInlineASMColonStyle : int8_t {
+ /// No break before inline ASM colon.
+ /// \code
+ /// asm volatile("string", : : val);
+ /// \endcode
+ BBIAS_Never,
+ /// Break before inline ASM colon if the line length is longer than column
+ /// limit.
+ /// \code
+ /// asm volatile("string", : : val);
+ /// asm("cmoveq %1, %2, %[result]"
+ /// : [result] "=r"(result)
+ /// : "r"(test), "r"(new), "[result]"(old));
+ /// \endcode
+ BBIAS_OnlyMultiline,
+ /// Always break before inline ASM colon.
+ /// \code
+ /// asm volatile("string",
+ /// :
+ /// : val);
+ /// \endcode
+ BBIAS_Always,
+ };
+
+ /// The inline ASM colon style to use.
+ /// \version 16
+ BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
+
+ /// If ``true``, break before a template closing bracket (``>``) when there is
+ /// a line break after the matching opening bracket (``<``).
+ /// \code
+ /// true:
+ /// template <typename Foo, typename Bar>
+ ///
+ /// template <typename Foo,
+ /// typename Bar>
+ ///
+ /// template <
+ /// typename Foo,
+ /// typename Bar
+ /// >
+ ///
+ /// false:
+ /// template <typename Foo, typename Bar>
+ ///
+ /// template <typename Foo,
+ /// typename Bar>
+ ///
+ /// template <
+ /// typename Foo,
+ /// typename Bar>
+ /// \endcode
+ /// \version 21
+ bool BreakBeforeTemplateCloser;
+
+ /// If ``true``, ternary operators will be placed after line breaks.
+ /// \code
+ /// true:
+ /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
+ /// ? firstValue
+ /// : SecondValueVeryVeryVeryVeryLong;
+ ///
+ /// false:
+ /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
+ /// firstValue :
+ /// SecondValueVeryVeryVeryVeryLong;
+ /// \endcode
+ /// \version 3.7
+ bool BreakBeforeTernaryOperators;
+
+ /// Different ways to break binary operations.
+ enum BreakBinaryOperationsStyle : int8_t {
+ /// Don't break binary operations
+ /// \code
+ /// aaa + bbbb * ccccc - ddddd +
+ /// eeeeeeeeeeeeeeee;
+ /// \endcode
+ BBO_Never,
+
+ /// Binary operations will either be all on the same line, or each operation
+ /// will have one line each.
+ /// \code
+ /// aaa +
+ /// bbbb *
+ /// ccccc -
+ /// ddddd +
+ /// eeeeeeeeeeeeeeee;
+ /// \endcode
+ BBO_OnePerLine,
+
+ /// Binary operations of a particular precedence that exceed the column
+ /// limit will have one line each.
+ /// \code
+ /// aaa +
+ /// bbbb * ccccc -
+ /// ddddd +
+ /// eeeeeeeeeeeeeeee;
+ /// \endcode
+ BBO_RespectPrecedence
+ };
+
+ /// A rule that specifies how to break a specific set of binary operators.
+ /// \version 23
+ struct BinaryOperationBreakRule {
+ /// The list of operators this rule applies to, e.g. ``&&``, ``||``, ``|``.
+ /// Alternative spellings (e.g. ``and`` for ``&&``) are accepted.
+ std::vector<tok::TokenKind> Operators;
+ /// The break style for these operators (defaults to ``OnePerLine``).
+ BreakBinaryOperationsStyle Style;
+ /// Minimum number of operands in a chain before the rule triggers.
+ /// For example, ``a && b && c`` is a chain of length 3.
+ /// ``0`` means always break (when the line is too long).
+ unsigned MinChainLength;
+ bool operator==(const BinaryOperationBreakRule &R) const {
+ return Operators == R.Operators && Style == R.Style &&
+ MinChainLength == R.MinChainLength;
+ }
+ bool operator!=(const BinaryOperationBreakRule &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Options for ``BreakBinaryOperations``.
+ ///
+ /// If specified as a simple string (e.g. ``OnePerLine``), it behaves like
+ /// the original enum and applies to all binary operators.
+ ///
+ /// If specified as a struct, allows per-operator configuration:
+ /// \code{.yaml}
+ /// BreakBinaryOperations:
+ /// Default: Never
+ /// PerOperator:
+ /// - Operators: ['&&', '||']
+ /// Style: OnePerLine
+ /// MinChainLength: 3
+ /// \endcode
+ /// \version 23
+ struct BreakBinaryOperationsOptions {
+ /// The default break style for operators not covered by ``PerOperator``.
+ BreakBinaryOperationsStyle Default;
+ /// Per-operator override rules.
+ std::vector<BinaryOperationBreakRule> PerOperator;
+ const BinaryOperationBreakRule *
+ findRuleForOperator(tok::TokenKind Kind) const {
+ for (const auto &Rule : PerOperator) {
+ if (llvm::find(Rule.Operators, Kind) != Rule.Operators.end())
+ return &Rule;
+ // clang-format splits ">>" into two ">" tokens for template parsing.
+ // Match ">" against ">>" rules so that per-operator rules for ">>"
+ // (stream extraction / right shift) work correctly.
+ if (Kind == tok::greater &&
+ llvm::find(Rule.Operators, tok::greatergreater) !=
+ Rule.Operators.end()) {
+ return &Rule;
+ }
+ }
+ return nullptr;
+ }
+ BreakBinaryOperationsStyle getStyleForOperator(tok::TokenKind Kind) const {
+ if (const auto *Rule = findRuleForOperator(Kind))
+ return Rule->Style;
+ return Default;
+ }
+ unsigned getMinChainLengthForOperator(tok::TokenKind Kind) const {
+ if (const auto *Rule = findRuleForOperator(Kind))
+ return Rule->MinChainLength;
+ return 0;
+ }
+ bool operator==(const BreakBinaryOperationsOptions &R) const {
+ return Default == R.Default && PerOperator == R.PerOperator;
+ }
+ bool operator!=(const BreakBinaryOperationsOptions &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// The break binary operations style to use.
+ /// \version 20
+ BreakBinaryOperationsOptions BreakBinaryOperations;
+
+ /// Different ways to break initializers.
+ enum BreakConstructorInitializersStyle : int8_t {
+ /// Break constructor initializers before the colon and after the commas.
+ /// \code
+ /// Constructor()
+ /// : initializer1(),
+ /// initializer2()
+ /// \endcode
+ BCIS_BeforeColon,
+ /// Break constructor initializers before the colon and commas, and align
+ /// the commas with the colon.
+ /// \code
+ /// Constructor()
+ /// : initializer1()
+ /// , initializer2()
+ /// \endcode
+ BCIS_BeforeComma,
+ /// Break constructor initializers after the colon and commas.
+ /// \code
+ /// Constructor() :
+ /// initializer1(),
+ /// initializer2()
+ /// \endcode
+ BCIS_AfterColon,
+ /// Break constructor initializers only after the commas.
+ /// \code
+ /// Constructor() : initializer1(),
+ /// initializer2()
+ /// \endcode
+ BCIS_AfterComma
+ };
+
+ /// The break constructor initializers style to use.
+ /// \version 5
+ BreakConstructorInitializersStyle BreakConstructorInitializers;
+
+ /// If ``true``, clang-format will always break before function definition
+ /// parameters.
+ /// \code
+ /// true:
+ /// void functionDefinition(
+ /// int A, int B) {}
+ ///
+ /// false:
+ /// void functionDefinition(int A, int B) {}
+ ///
+ /// \endcode
+ /// \version 19
+ bool BreakFunctionDefinitionParameters;
+
+ /// Break after each annotation on a field in Java files.
+ /// \code{.java}
+ /// true: false:
+ /// @Partial vs. @Partial @Mock DataLoad loader;
+ /// @Mock
+ /// DataLoad loader;
+ /// \endcode
+ /// \version 3.8
+ bool BreakAfterJavaFieldAnnotations;
+
+ /// Allow breaking string literals when formatting.
+ ///
+ /// In C, C++, and Objective-C:
+ /// \code
+ /// true:
+ /// const char* x = "veryVeryVeryVeryVeryVe"
+ /// "ryVeryVeryVeryVeryVery"
+ /// "VeryLongString";
+ ///
+ /// false:
+ /// const char* x =
+ /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
+ /// \endcode
+ ///
+ /// In C# and Java:
+ /// \code
+ /// true:
+ /// string x = "veryVeryVeryVeryVeryVe" +
+ /// "ryVeryVeryVeryVeryVery" +
+ /// "VeryLongString";
+ ///
+ /// false:
+ /// string x =
+ /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
+ /// \endcode
+ ///
+ /// C# interpolated strings are not broken.
+ ///
+ /// In Verilog:
+ /// \code
+ /// true:
+ /// string x = {"veryVeryVeryVeryVeryVe",
+ /// "ryVeryVeryVeryVeryVery",
+ /// "VeryLongString"};
+ ///
+ /// false:
+ /// string x =
+ /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
+ /// \endcode
+ ///
+ /// \version 3.9
+ bool BreakStringLiterals;
+
+ /// The column limit.
+ ///
+ /// A column limit of ``0`` means that there is no column limit. In this case,
+ /// clang-format will respect the input's line breaking decisions within
+ /// statements unless they contradict other rules.
+ /// \version 3.7
+ unsigned ColumnLimit;
+
+ /// A regular expression that describes comments with special meaning,
+ /// which should not be split into lines or otherwise changed.
+ /// \code
+ /// // CommentPragmas: '^ FOOBAR pragma:'
+ /// // Will leave the following line unaffected
+ /// #include <vector> // FOOBAR pragma: keep
+ /// \endcode
+ /// \version 3.7
+ std::string CommentPragmas;
+
+ /// Different ways to break inheritance list.
+ enum BreakInheritanceListStyle : int8_t {
+ /// Break inheritance list before the colon and after the commas.
+ /// \code
+ /// class Foo
+ /// : Base1,
+ /// Base2
+ /// {};
+ /// \endcode
+ BILS_BeforeColon,
+ /// Break inheritance list before the colon and commas, and align
+ /// the commas with the colon.
+ /// \code
+ /// class Foo
+ /// : Base1
+ /// , Base2
+ /// {};
+ /// \endcode
+ BILS_BeforeComma,
+ /// Break inheritance list after the colon and commas.
+ /// \code
+ /// class Foo :
+ /// Base1,
+ /// Base2
+ /// {};
+ /// \endcode
+ BILS_AfterColon,
+ /// Break inheritance list only after the commas.
+ /// \code
+ /// class Foo : Base1,
+ /// Base2
+ /// {};
+ /// \endcode
+ BILS_AfterComma,
+ };
+
+ /// The inheritance list style to use.
+ /// \version 7
+ BreakInheritanceListStyle BreakInheritanceList;
+
+ /// The template declaration breaking style to use.
+ /// \version 19
+ BreakTemplateDeclarationsStyle BreakTemplateDeclarations;
+
+ /// If ``true``, consecutive namespace declarations will be on the same
+ /// line. If ``false``, each namespace is declared on a new line.
+ /// \code
+ /// true:
+ /// namespace Foo { namespace Bar {
+ /// }}
+ ///
+ /// false:
+ /// namespace Foo {
+ /// namespace Bar {
+ /// }
+ /// }
+ /// \endcode
+ ///
+ /// If it does not fit on a single line, the overflowing namespaces get
+ /// wrapped:
+ /// \code
+ /// namespace Foo { namespace Bar {
+ /// namespace Extra {
+ /// }}}
+ /// \endcode
+ /// \version 5
+ bool CompactNamespaces;
+
+ /// This option is **deprecated**. See ``CurrentLine`` of
+ /// ``PackConstructorInitializers``.
+ /// \version 3.7
+ // bool ConstructorInitializerAllOnOneLineOrOnePerLine;
+
+ /// The number of characters to use for indentation of constructor
+ /// initializer lists as well as inheritance lists.
+ /// \version 3.7
+ unsigned ConstructorInitializerIndentWidth;
+
+ /// Indent width for line continuations.
+ /// \code
+ /// ContinuationIndentWidth: 2
+ ///
+ /// int i = // VeryVeryVeryVeryVeryLongComment
+ /// longFunction( // Again a long comment
+ /// arg);
+ /// \endcode
+ /// \version 3.7
+ unsigned ContinuationIndentWidth;
+
+ /// Different ways to handle braced lists.
+ enum BracedListStyle : int8_t {
+ /// Best suited for pre C++11 braced lists.
+ ///
+ /// * Spaces inside the braced list.
+ /// * Line break before the closing brace.
+ /// * Indentation with the block indent.
+ ///
+ /// \code
+ /// vector<int> x{ 1, 2, 3, 4 };
+ /// vector<T> x{ {}, {}, {}, {} };
+ /// f(MyMap[{ composite, key }]);
+ /// new int[3]{ 1, 2, 3 };
+ /// Type name{ // Comment
+ /// value
+ /// };
+ /// \endcode
+ BLS_Block,
+ /// Best suited for C++11 braced lists.
+ ///
+ /// * No spaces inside the braced list.
+ /// * No line break before the closing brace.
+ /// * Indentation with the continuation indent.
+ ///
+ /// Fundamentally, C++11 braced lists are formatted exactly like function
+ /// calls would be formatted in their place. If the braced list follows a
+ /// name (e.g. a type or variable name), clang-format formats as if the
+ /// ``{}`` were the parentheses of a function call with that name. If there
+ /// is no name, a zero-length name is assumed.
+ /// \code
+ /// vector<int> x{1, 2, 3, 4};
+ /// vector<T> x{{}, {}, {}, {}};
+ /// f(MyMap[{composite, key}]);
+ /// new int[3]{1, 2, 3};
+ /// Type name{ // Comment
+ /// value};
+ /// \endcode
+ BLS_FunctionCall,
+ /// Same as ``FunctionCall``, except for the handling of a comment at the
+ /// begin, it then aligns everything following with the comment.
+ ///
+ /// * No spaces inside the braced list. (Even for a comment at the first
+ /// position.)
+ /// * No line break before the closing brace.
+ /// * Indentation with the continuation indent, except when followed by a
+ /// line comment, then it uses the block indent.
+ ///
+ /// \code
+ /// vector<int> x{1, 2, 3, 4};
+ /// vector<T> x{{}, {}, {}, {}};
+ /// f(MyMap[{composite, key}]);
+ /// new int[3]{1, 2, 3};
+ /// Type name{// Comment
+ /// value};
+ /// \endcode
+ BLS_AlignFirstComment,
+ };
+
+ /// The style to handle braced lists.
+ /// \version 3.4
+ BracedListStyle Cpp11BracedListStyle;
+
+ /// This option is **deprecated**. See ``DeriveLF`` and ``DeriveCRLF`` of
+ /// ``LineEnding``.
+ /// \version 10
+ // bool DeriveLineEnding;
+
+ /// If ``true``, analyze the formatted file for the most common
+ /// alignment of ``&`` and ``*``.
+ /// Pointer and reference alignment styles are going to be updated according
+ /// to the preferences found in the file.
+ /// ``PointerAlignment`` is then used only as fallback.
+ /// \version 3.7
+ bool DerivePointerAlignment;
+
+ /// Disables formatting completely.
+ /// \version 3.7
+ bool DisableFormat;
+
+ /// Different styles for empty line after access modifiers.
+ /// ``EmptyLineBeforeAccessModifier`` configuration handles the number of
+ /// empty lines between two access modifiers.
+ enum EmptyLineAfterAccessModifierStyle : int8_t {
+ /// Remove all empty lines after access modifiers.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ /// protected:
+ /// int j;
+ /// /* comment */
+ /// public:
+ /// foo() {}
+ /// private:
+ /// protected:
+ /// };
+ /// \endcode
+ ELAAMS_Never,
+ /// Keep existing empty lines after access modifiers.
+ /// MaxEmptyLinesToKeep is applied instead.
+ ELAAMS_Leave,
+ /// Always add empty line after access modifiers if there are none.
+ /// MaxEmptyLinesToKeep is applied also.
+ /// \code
+ /// struct foo {
+ /// private:
+ ///
+ /// int i;
+ /// protected:
+ ///
+ /// int j;
+ /// /* comment */
+ /// public:
+ ///
+ /// foo() {}
+ /// private:
+ ///
+ /// protected:
+ ///
+ /// };
+ /// \endcode
+ ELAAMS_Always,
+ };
+
+ /// Defines when to put an empty line after access modifiers.
+ /// ``EmptyLineBeforeAccessModifier`` configuration handles the number of
+ /// empty lines between two access modifiers.
+ /// \version 13
+ EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier;
+
+ /// Different styles for empty line before access modifiers.
+ enum EmptyLineBeforeAccessModifierStyle : int8_t {
+ /// Remove all empty lines before access modifiers.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ /// protected:
+ /// int j;
+ /// /* comment */
+ /// public:
+ /// foo() {}
+ /// private:
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_Never,
+ /// Keep existing empty lines before access modifiers.
+ ELBAMS_Leave,
+ /// Add empty line only when access modifier starts a new logical block.
+ /// Logical block is a group of one or more member fields or functions.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ ///
+ /// protected:
+ /// int j;
+ /// /* comment */
+ /// public:
+ /// foo() {}
+ ///
+ /// private:
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_LogicalBlock,
+ /// Always add empty line before access modifiers unless access modifier
+ /// is at the start of struct or class definition.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ ///
+ /// protected:
+ /// int j;
+ /// /* comment */
+ ///
+ /// public:
+ /// foo() {}
+ ///
+ /// private:
+ ///
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_Always,
+ };
+
+ /// Defines in which cases to put empty line before access modifiers.
+ /// \version 12
+ EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
+
+ /// Styles for ``enum`` trailing commas.
+ enum EnumTrailingCommaStyle : int8_t {
+ /// Don't insert or remove trailing commas.
+ /// \code
+ /// enum { a, b, c, };
+ /// enum Color { red, green, blue };
+ /// \endcode
+ ETC_Leave,
+ /// Insert trailing commas.
+ /// \code
+ /// enum { a, b, c, };
+ /// enum Color { red, green, blue, };
+ /// \endcode
+ ETC_Insert,
+ /// Remove trailing commas.
+ /// \code
+ /// enum { a, b, c };
+ /// enum Color { red, green, blue };
+ /// \endcode
+ ETC_Remove,
+ };
+
+ /// Insert a comma (if missing) or remove the comma at the end of an ``enum``
+ /// enumerator list.
+ /// \warning
+ /// Setting this option to any value other than ``Leave`` could lead to
+ /// incorrect code formatting due to clang-format's lack of complete semantic
+ /// information. As such, extra care should be taken to review code changes
+ /// made by this option.
+ /// \endwarning
+ /// \version 21
+ EnumTrailingCommaStyle EnumTrailingComma;
+
+ /// If ``true``, clang-format detects whether function calls and
+ /// definitions are formatted with one parameter per line.
+ ///
+ /// Each call can be bin-packed, one-per-line or inconclusive. If it is
+ /// inconclusive, e.g. completely on one line, but a decision needs to be
+ /// made, clang-format analyzes whether there are other bin-packed cases in
+ /// the input file and act accordingly.
+ ///
+ /// \note
+ /// This is an experimental flag, that might go away or be renamed. Do
+ /// not use this in config files, etc. Use at your own risk.
+ /// \endnote
+ /// \version 3.7
+ bool ExperimentalAutoDetectBinPacking;
+
+ /// If ``true``, clang-format adds missing namespace end comments for
+ /// namespaces and fixes invalid existing ones. This doesn't affect short
+ /// namespaces, which are controlled by ``ShortNamespaceLines``.
+ /// \code
+ /// true: false:
+ /// namespace longNamespace { vs. namespace longNamespace {
+ /// void foo(); void foo();
+ /// void bar(); void bar();
+ /// } // namespace a }
+ /// namespace shortNamespace { namespace shortNamespace {
+ /// void baz(); void baz();
+ /// } }
+ /// \endcode
+ /// \version 5
+ bool FixNamespaceComments;
+
+ /// A vector of macros that should be interpreted as foreach loops
+ /// instead of as function calls.
+ ///
+ /// These are expected to be macros of the form:
+ /// \code
+ /// FOREACH(<variable-declaration>, ...)
+ /// <loop-body>
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// ForEachMacros: [RANGES_FOR, FOREACH]
+ /// \endcode
+ ///
+ /// For example: BOOST_FOREACH.
+ /// \version 3.7
+ std::vector<std::string> ForEachMacros;
+
+ tooling::IncludeStyle IncludeStyle;
+
+ /// A vector of macros that should be interpreted as conditionals
+ /// instead of as function calls.
+ ///
+ /// These are expected to be macros of the form:
+ /// \code
+ /// IF(...)
+ /// <conditional-body>
+ /// else IF(...)
+ /// <conditional-body>
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// IfMacros: [IF]
+ /// \endcode
+ ///
+ /// For example: `KJ_IF_MAYBE
+ /// <https://github.com/capnproto/capnproto/blob/master/kjdoc/tour.md#maybes>`_
+ /// \version 13
+ std::vector<std::string> IfMacros;
+
+ /// Specify whether access modifiers should have their own indentation level.
+ ///
+ /// When ``false``, access modifiers are indented (or outdented) relative to
+ /// the record members, respecting the ``AccessModifierOffset``. Record
+ /// members are indented one level below the record.
+ /// When ``true``, access modifiers get their own indentation level. As a
+ /// consequence, record members are always indented 2 levels below the record,
+ /// regardless of the access modifier presence. Value of the
+ /// ``AccessModifierOffset`` is ignored.
+ /// \code
+ /// false: true:
+ /// class C { vs. class C {
+ /// class D { class D {
+ /// void bar(); void bar();
+ /// protected: protected:
+ /// D(); D();
+ /// }; };
+ /// public: public:
+ /// C(); C();
+ /// }; };
+ /// void foo() { void foo() {
+ /// return 1; return 1;
+ /// } }
+ /// \endcode
+ /// \version 13
+ bool IndentAccessModifiers;
+
+ /// Indent case label blocks one level from the case label.
+ ///
+ /// When ``false``, the block following the case label uses the same
+ /// indentation level as for the case label, treating the case label the same
+ /// as an if-statement.
+ /// When ``true``, the block gets indented as a scope block.
+ /// \code
+ /// false: true:
+ /// switch (fool) { vs. switch (fool) {
+ /// case 1: { case 1:
+ /// bar(); {
+ /// } break; bar();
+ /// default: { }
+ /// plop(); break;
+ /// } default:
+ /// } {
+ /// plop();
+ /// }
+ /// }
+ /// \endcode
+ /// \version 11
+ bool IndentCaseBlocks;
+
+ /// Indent case labels one level from the switch statement.
+ ///
+ /// When ``false``, use the same indentation level as for the switch
+ /// statement. Switch statement body is always indented one level more than
+ /// case labels (except the first block following the case label, which
+ /// itself indents the code - unless IndentCaseBlocks is enabled).
+ /// \code
+ /// false: true:
+ /// switch (fool) { vs. switch (fool) {
+ /// case 1: case 1:
+ /// bar(); bar();
+ /// break; break;
+ /// default: default:
+ /// plop(); plop();
+ /// } }
+ /// \endcode
+ /// \version 3.3
+ bool IndentCaseLabels;
+
+ /// If ``true``, clang-format will indent the body of an ``export { ... }``
+ /// block. This doesn't affect the formatting of anything else related to
+ /// exported declarations.
+ /// \code
+ /// true: false:
+ /// export { vs. export {
+ /// void foo(); void foo();
+ /// void bar(); void bar();
+ /// } }
+ /// \endcode
+ /// \version 20
+ bool IndentExportBlock;
+
+ /// Indents extern blocks
+ enum IndentExternBlockStyle : int8_t {
+ /// Backwards compatible with AfterExternBlock's indenting.
+ /// \code
+ /// IndentExternBlock: AfterExternBlock
+ /// BraceWrapping.AfterExternBlock: true
+ /// extern "C"
+ /// {
+ /// void foo();
+ /// }
+ /// \endcode
+ ///
+ /// \code
+ /// IndentExternBlock: AfterExternBlock
+ /// BraceWrapping.AfterExternBlock: false
+ /// extern "C" {
+ /// void foo();
+ /// }
+ /// \endcode
+ IEBS_AfterExternBlock,
+ /// Does not indent extern blocks.
+ /// \code
+ /// extern "C" {
+ /// void foo();
+ /// }
+ /// \endcode
+ IEBS_NoIndent,
+ /// Indents extern blocks.
+ /// \code
+ /// extern "C" {
+ /// void foo();
+ /// }
+ /// \endcode
+ IEBS_Indent,
+ };
+
+ /// IndentExternBlockStyle is the type of indenting of extern blocks.
+ /// \version 11
+ IndentExternBlockStyle IndentExternBlock;
+
+ /// Options for indenting goto labels.
+ enum IndentGotoLabelStyle : int8_t {
+ /// Do not indent goto labels.
+ /// \code
+ /// int f() {
+ /// if (foo()) {
+ /// label1:
+ /// bar();
+ /// }
+ /// label2:
+ /// return 1;
+ /// }
+ /// \endcode
+ IGLS_NoIndent,
+ /// Indent goto labels to the enclosing block (previous indenting level).
+ /// \code
+ /// int f() {
+ /// if (foo()) {
+ /// label1:
+ /// bar();
+ /// }
+ /// label2:
+ /// return 1;
+ /// }
+ /// \endcode
+ IGLS_OuterIndent,
+ /// Indent goto labels to the surrounding statements (current indenting
+ /// level).
+ /// \code
+ /// int f() {
+ /// if (foo()) {
+ /// label1:
+ /// bar();
+ /// }
+ /// label2:
+ /// return 1;
+ /// }
+ /// \endcode
+ IGLS_InnerIndent,
+ /// Indent goto labels to half the indentation of the surrounding code.
+ /// If the indentation width is an odd number, it will round up.
+ /// \code
+ /// int f() {
+ /// if (foo()) {
+ /// label1:
+ /// bar();
+ /// }
+ /// label2:
+ /// return 1;
+ /// }
+ /// \endcode
+ IGLS_HalfIndent,
+ };
+
+ /// The goto label indenting style to use.
+ /// \version 10
+ IndentGotoLabelStyle IndentGotoLabels;
+
+ /// Options for indenting preprocessor directives.
+ enum PPDirectiveIndentStyle : int8_t {
+ /// Does not indent any directives.
+ /// \code
+ /// #if FOO
+ /// #if BAR
+ /// #include <foo>
+ /// #endif
+ /// #endif
+ /// \endcode
+ PPDIS_None,
+ /// Indents directives after the hash.
+ /// \code
+ /// #if FOO
+ /// # if BAR
+ /// # include <foo>
+ /// # endif
+ /// #endif
+ /// \endcode
+ PPDIS_AfterHash,
+ /// Indents directives before the hash.
+ /// \code
+ /// #if FOO
+ /// #if BAR
+ /// #include <foo>
+ /// #endif
+ /// #endif
+ /// \endcode
+ PPDIS_BeforeHash,
+ /// Leaves indentation of directives as-is.
+ /// \note
+ /// Ignores ``PPIndentWidth``.
+ /// \endnote
+ /// \code
+ /// #if FOO
+ /// #if BAR
+ /// #include <foo>
+ /// #endif
+ /// #endif
+ /// \endcode
+ PPDIS_Leave
+ };
+
+ /// The preprocessor directive indenting style to use.
+ /// \version 6
+ PPDirectiveIndentStyle IndentPPDirectives;
+
+ /// Indent the requires clause in a template. This only applies when
+ /// ``RequiresClausePosition`` is ``OwnLine``, ``OwnLineWithBrace``,
+ /// or ``WithFollowing``.
+ ///
+ /// In clang-format 12, 13 and 14 it was named ``IndentRequires``.
+ /// \code
+ /// true:
+ /// template <typename It>
+ /// requires Iterator<It>
+ /// void sort(It begin, It end) {
+ /// //....
+ /// }
+ ///
+ /// false:
+ /// template <typename It>
+ /// requires Iterator<It>
+ /// void sort(It begin, It end) {
+ /// //....
+ /// }
+ /// \endcode
+ /// \version 15
+ bool IndentRequiresClause;
+
+ /// The number of columns to use for indentation.
+ /// \code
+ /// IndentWidth: 3
+ ///
+ /// void f() {
+ /// someFunction();
+ /// if (true, false) {
+ /// f();
+ /// }
+ /// }
+ /// \endcode
+ /// \version 3.7
+ unsigned IndentWidth;
+
+ /// Indent if a function definition or declaration is wrapped after the
+ /// type.
+ /// \code
+ /// true:
+ /// LoooooooooooooooooooooooooooooooooooooooongReturnType
+ /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
+ ///
+ /// false:
+ /// LoooooooooooooooooooooooooooooooooooooooongReturnType
+ /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
+ /// \endcode
+ /// \version 3.7
+ bool IndentWrappedFunctionNames;
+
+ /// Insert braces after control statements (``if``, ``else``, ``for``, ``do``,
+ /// and ``while``) in C++ unless the control statements are inside macro
+ /// definitions or the braces would enclose preprocessor directives.
+ /// \warning
+ /// Setting this option to ``true`` could lead to incorrect code formatting
+ /// due to clang-format's lack of complete semantic information. As such,
+ /// extra care should be taken to review code changes made by this option.
+ /// \endwarning
+ /// \code
+ /// false: true:
+ ///
+ /// if (isa<FunctionDecl>(D)) vs. if (isa<FunctionDecl>(D)) {
+ /// handleFunctionDecl(D); handleFunctionDecl(D);
+ /// else if (isa<VarDecl>(D)) } else if (isa<VarDecl>(D)) {
+ /// handleVarDecl(D); handleVarDecl(D);
+ /// else } else {
+ /// return; return;
+ /// }
+ ///
+ /// while (i--) vs. while (i--) {
+ /// for (auto *A : D.attrs()) for (auto *A : D.attrs()) {
+ /// handleAttr(A); handleAttr(A);
+ /// }
+ /// }
+ ///
+ /// do vs. do {
+ /// --i; --i;
+ /// while (i); } while (i);
+ /// \endcode
+ /// \version 15
+ bool InsertBraces;
+
+ /// Insert a newline at end of file if missing.
+ /// \version 16
+ bool InsertNewlineAtEOF;
+
+ /// The style of inserting trailing commas into container literals.
+ enum TrailingCommaStyle : int8_t {
+ /// Do not insert trailing commas.
+ TCS_None,
+ /// Insert trailing commas in container literals that were wrapped over
+ /// multiple lines. Note that this is conceptually incompatible with
+ /// bin-packing, because the trailing comma is used as an indicator
+ /// that a container should be formatted one-per-line (i.e. not bin-packed).
+ /// So inserting a trailing comma counteracts bin-packing.
+ TCS_Wrapped,
+ };
+
+ /// If set to ``TCS_Wrapped`` will insert trailing commas in container
+ /// literals (arrays and objects) that wrap across multiple lines.
+ /// It is currently only available for JavaScript
+ /// and disabled by default ``TCS_None``.
+ /// ``InsertTrailingCommas`` cannot be used together with ``BinPackArguments``
+ /// as inserting the comma disables bin-packing.
+ /// \code
+ /// TSC_Wrapped:
+ /// const someArray = [
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
+ /// aaaaaaaaaaaaaaaaaaaaaaaaaa,
+ /// // ^ inserted
+ /// ]
+ /// \endcode
+ /// \version 11
+ TrailingCommaStyle InsertTrailingCommas;
+
+ /// Separator format of integer literals of different bases.
+ ///
+ /// If negative, remove separators. If ``0``, leave the literal as is. If
+ /// positive, insert separators between digits starting from the rightmost
+ /// digit.
+ ///
+ /// For example, the config below will leave separators in binary literals
+ /// alone, insert separators in decimal literals to separate the digits into
+ /// groups of 3, and remove separators in hexadecimal literals.
+ /// \code
+ /// IntegerLiteralSeparator:
+ /// Binary: 0
+ /// Decimal: 3
+ /// Hex: -1
+ /// \endcode
+ ///
+ /// You can also specify a minimum number of digits
+ /// (``BinaryMinDigitsInsert``, ``DecimalMinDigitsInsert``, and
+ /// ``HexMinDigitsInsert``) the integer literal must have in order for the
+ /// separators to be inserted, and a maximum number of digits
+ /// (``BinaryMaxDigitsRemove``, ``DecimalMaxDigitsRemove``, and
+ /// ``HexMaxDigitsRemove``) until the separators are removed. This divides the
+ /// literals in 3 regions, always without separator (up until including
+ /// ``xxxMaxDigitsRemove``), maybe with, or without separators (up until
+ /// excluding ``xxxMinDigitsInsert``), and finally always with separators.
+ /// \note
+ /// ``BinaryMinDigits``, ``DecimalMinDigits``, and ``HexMinDigits`` are
+ /// deprecated and renamed to ``BinaryMinDigitsInsert``,
+ /// ``DecimalMinDigitsInsert``, and ``HexMinDigitsInsert``, respectively.
+ /// \endnote
+ struct IntegerLiteralSeparatorStyle {
+ /// Format separators in binary literals.
+ /// \code{.text}
+ /// /* -1: */ b = 0b100111101101;
+ /// /* 0: */ b = 0b10011'11'0110'1;
+ /// /* 3: */ b = 0b100'111'101'101;
+ /// /* 4: */ b = 0b1001'1110'1101;
+ /// \endcode
+ int8_t Binary;
+ /// Format separators in binary literals with a minimum number of digits.
+ /// \code{.text}
+ /// // Binary: 3
+ /// // BinaryMinDigitsInsert: 7
+ /// b1 = 0b101101;
+ /// b2 = 0b1'101'101;
+ /// \endcode
+ int8_t BinaryMinDigitsInsert;
+ /// Remove separators in binary literals with a maximum number of digits.
+ /// \code{.text}
+ /// // Binary: 3
+ /// // BinaryMinDigitsInsert: 7
+ /// // BinaryMaxDigitsRemove: 4
+ /// b0 = 0b1011; // Always removed.
+ /// b1 = 0b101101; // Not added.
+ /// b2 = 0b1'01'101; // Not removed, not corrected.
+ /// b3 = 0b1'101'101; // Always added.
+ /// b4 = 0b10'1101; // Corrected to 0b101'101.
+ /// \endcode
+ int8_t BinaryMaxDigitsRemove;
+ /// Format separators in decimal literals.
+ /// \code{.text}
+ /// /* -1: */ d = 18446744073709550592ull;
+ /// /* 0: */ d = 184467'440737'0'95505'92ull;
+ /// /* 3: */ d = 18'446'744'073'709'550'592ull;
+ /// \endcode
+ int8_t Decimal;
+ /// Format separators in decimal literals with a minimum number of digits.
+ /// \code{.text}
+ /// // Decimal: 3
+ /// // DecimalMinDigitsInsert: 5
+ /// d1 = 2023;
+ /// d2 = 10'000;
+ /// \endcode
+ int8_t DecimalMinDigitsInsert;
+ /// Remove separators in decimal literals with a maximum number of digits.
+ /// \code{.text}
+ /// // Decimal: 3
+ /// // DecimalMinDigitsInsert: 7
+ /// // DecimalMaxDigitsRemove: 4
+ /// d0 = 2023; // Always removed.
+ /// d1 = 123456; // Not added.
+ /// d2 = 1'23'456; // Not removed, not corrected.
+ /// d3 = 5'000'000; // Always added.
+ /// d4 = 1'23'45; // Corrected to 12'345.
+ /// \endcode
+ int8_t DecimalMaxDigitsRemove;
+ /// Format separators in hexadecimal literals.
+ /// \code{.text}
+ /// /* -1: */ h = 0xDEADBEEFDEADBEEFuz;
+ /// /* 0: */ h = 0xDEAD'BEEF'DE'AD'BEE'Fuz;
+ /// /* 2: */ h = 0xDE'AD'BE'EF'DE'AD'BE'EFuz;
+ /// \endcode
+ int8_t Hex;
+ /// Format separators in hexadecimal literals with a minimum number of
+ /// digits.
+ /// \code{.text}
+ /// // Hex: 2
+ /// // HexMinDigitsInsert: 6
+ /// h1 = 0xABCDE;
+ /// h2 = 0xAB'CD'EF;
+ /// \endcode
+ int8_t HexMinDigitsInsert;
+ /// Remove separators in hexadecimal literals with a maximum number of
+ /// digits.
+ /// \code{.text}
+ /// // Hex: 2
+ /// // HexMinDigitsInsert: 6
+ /// // HexMaxDigitsRemove: 4
+ /// h0 = 0xAFFE; // Always removed.
+ /// h1 = 0xABCDE; // Not added.
+ /// h2 = 0xABC'DE; // Not removed, not corrected.
+ /// h3 = 0xAB'CD'EF; // Always added.
+ /// h4 = 0xABCD'E; // Corrected to 0xA'BC'DE.
+ /// \endcode
+ int8_t HexMaxDigitsRemove;
+ bool operator==(const IntegerLiteralSeparatorStyle &R) const {
+ return Binary == R.Binary &&
+ BinaryMinDigitsInsert == R.BinaryMinDigitsInsert &&
+ BinaryMaxDigitsRemove == R.BinaryMaxDigitsRemove &&
+ Decimal == R.Decimal &&
+ DecimalMinDigitsInsert == R.DecimalMinDigitsInsert &&
+ DecimalMaxDigitsRemove == R.DecimalMaxDigitsRemove &&
+ Hex == R.Hex && HexMinDigitsInsert == R.HexMinDigitsInsert &&
+ HexMaxDigitsRemove == R.HexMaxDigitsRemove;
+ }
+ bool operator!=(const IntegerLiteralSeparatorStyle &R) const {
+ return !operator==(R);
+ }
+ };
+
+ /// Format integer literal separators (``'`` for C/C++ and ``_`` for C#, Java,
+ /// and JavaScript).
+ /// \version 16
+ IntegerLiteralSeparatorStyle IntegerLiteralSeparator;
+
+ /// A vector of prefixes ordered by the desired groups for Java imports.
+ ///
+ /// One group's prefix can be a subset of another - the longest prefix is
+ /// always matched. Within a group, the imports are ordered lexicographically.
+ /// Static imports are grouped separately and follow the same group rules.
+ /// By default, static imports are placed before non-static imports,
+ /// but this behavior is changed by another option,
+ /// ``SortJavaStaticImport``.
+ ///
+ /// In the .clang-format configuration file, this can be configured like
+ /// in the following yaml example. This will result in imports being
+ /// formatted as in the Java example below.
+ /// \code{.yaml}
+ /// JavaImportGroups: [com.example, com, org]
+ /// \endcode
+ ///
+ /// \code{.java}
+ /// import static com.example.function1;
+ ///
+ /// import static com.test.function2;
+ ///
+ /// import static org.example.function3;
+ ///
+ /// import com.example.ClassA;
+ /// import com.example.Test;
+ /// import com.example.a.ClassB;
+ ///
+ /// import com.test.ClassC;
+ ///
+ /// import org.example.ClassD;
+ /// \endcode
+ /// \version 8
+ std::vector<std::string> JavaImportGroups;
+
+ /// Quotation styles for JavaScript strings. Does not affect template
+ /// strings.
+ enum JavaScriptQuoteStyle : int8_t {
+ /// Leave string quotes as they are.
+ /// \code{.js}
+ /// string1 = "foo";
+ /// string2 = 'bar';
+ /// \endcode
+ JSQS_Leave,
+ /// Always use single quotes.
+ /// \code{.js}
+ /// string1 = 'foo';
+ /// string2 = 'bar';
+ /// \endcode
+ JSQS_Single,
+ /// Always use double quotes.
+ /// \code{.js}
+ /// string1 = "foo";
+ /// string2 = "bar";
+ /// \endcode
+ JSQS_Double
+ };
+
+ /// The JavaScriptQuoteStyle to use for JavaScript strings.
+ /// \version 3.9
+ JavaScriptQuoteStyle JavaScriptQuotes;
+
+ // clang-format off
+ /// Whether to wrap JavaScript import/export statements.
+ /// \code{.js}
+ /// true:
+ /// import {
+ /// VeryLongImportsAreAnnoying,
+ /// VeryLongImportsAreAnnoying,
+ /// VeryLongImportsAreAnnoying,
+ /// } from "some/module.js"
+ ///
+ /// false:
+ /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
+ /// \endcode
+ /// \version 3.9
+ bool JavaScriptWrapImports;
+ // clang-format on
+
+ /// Options regarding which empty lines are kept.
+ ///
+ /// For example, the config below will remove empty lines at start of the
+ /// file, end of the file, and start of blocks.
+ ///
+ /// \code
+ /// KeepEmptyLines:
+ /// AtEndOfFile: false
+ /// AtStartOfBlock: false
+ /// AtStartOfFile: false
+ /// \endcode
+ struct KeepEmptyLinesStyle {
+ /// Keep empty lines at end of file.
+ bool AtEndOfFile;
+ /// Keep empty lines at start of a block.
+ /// \code
+ /// true: false:
+ /// if (foo) { vs. if (foo) {
+ /// bar();
+ /// bar(); }
+ /// }
+ /// \endcode
+ bool AtStartOfBlock;
+ /// Keep empty lines at start of file.
+ bool AtStartOfFile;
+ bool operator==(const KeepEmptyLinesStyle &R) const {
+ return AtEndOfFile == R.AtEndOfFile &&
+ AtStartOfBlock == R.AtStartOfBlock &&
+ AtStartOfFile == R.AtStartOfFile;
+ }
+ };
+ /// Which empty lines are kept. See ``MaxEmptyLinesToKeep`` for how many
+ /// consecutive empty lines are kept.
+ /// \version 19
+ KeepEmptyLinesStyle KeepEmptyLines;
+
+ /// This option is **deprecated**. See ``AtEndOfFile`` of ``KeepEmptyLines``.
+ /// \version 17
+ // bool KeepEmptyLinesAtEOF;
+
+ /// This option is **deprecated**. See ``AtStartOfBlock`` of
+ /// ``KeepEmptyLines``.
+ /// \version 3.7
+ // bool KeepEmptyLinesAtTheStartOfBlocks;
+
+ /// Keep the form feed character if it's immediately preceded and followed by
+ /// a newline. Multiple form feeds and newlines within a whitespace range are
+ /// replaced with a single newline and form feed followed by the remaining
+ /// newlines. (See
+ /// www.gnu.org/prep/standards/html_node/Formatting.html#:~:text=formfeed.)
+ /// \version 20
+ bool KeepFormFeed;
+
+ /// Indentation logic for lambda bodies.
+ enum LambdaBodyIndentationKind : int8_t {
+ /// Align lambda body relative to the lambda signature. This is the default.
+ /// \code
+ /// someMethod(
+ /// [](SomeReallyLongLambdaSignatureArgument foo) {
+ /// return;
+ /// });
+ /// \endcode
+ LBI_Signature,
+ /// For statements within block scope, align lambda body relative to the
+ /// indentation level of the outer scope the lambda signature resides in.
+ /// \code
+ /// someMethod(
+ /// [](SomeReallyLongLambdaSignatureArgument foo) {
+ /// return;
+ /// });
+ ///
+ /// someMethod(someOtherMethod(
+ /// [](SomeReallyLongLambdaSignatureArgument foo) {
+ /// return;
+ /// }));
+ /// \endcode
+ LBI_OuterScope,
+ };
+
+ /// The indentation style of lambda bodies. ``Signature`` (the default)
+ /// causes the lambda body to be indented one additional level relative to
+ /// the indentation level of the signature. ``OuterScope`` forces the lambda
+ /// body to be indented one additional level relative to the parent scope
+ /// containing the lambda signature.
+ /// \version 13
+ LambdaBodyIndentationKind LambdaBodyIndentation;
+
+ /// Supported languages.
+ ///
+ /// When stored in a configuration file, specifies the language, that the
+ /// configuration targets. When passed to the ``reformat()`` function, enables
+ /// syntax features specific to the language.
+ enum LanguageKind : int8_t {
+ /// Do not use.
+ LK_None,
+ /// Should be used for C.
+ LK_C,
+ /// Should be used for C++.
+ LK_Cpp,
+ /// Should be used for C#.
+ LK_CSharp,
+ /// Should be used for Java.
+ LK_Java,
+ /// Should be used for JavaScript.
+ LK_JavaScript,
+ /// Should be used for JSON.
+ LK_Json,
+ /// Should be used for Objective-C, Objective-C++.
+ LK_ObjC,
+ /// Should be used for Protocol Buffers
+ /// (https://developers.google.com/protocol-buffers/).
+ LK_Proto,
+ /// Should be used for TableGen code.
+ LK_TableGen,
+ /// Should be used for Protocol Buffer messages in text format
+ /// (https://developers.google.com/protocol-buffers/).
+ LK_TextProto,
+ /// Should be used for Verilog and SystemVerilog.
+ /// https://standards.ieee.org/ieee/1800/6700/
+ /// https://sci-hub.st/10.1109/IEEESTD.2018.8299595
+ LK_Verilog
+ };
+ bool isCpp() const {
+ return Language == LK_Cpp || Language == LK_C || Language == LK_ObjC;
+ }
+ bool isCSharp() const { return Language == LK_CSharp; }
+ bool isJson() const { return Language == LK_Json; }
+ bool isJava() const { return Language == LK_Java; }
+ bool isJavaScript() const { return Language == LK_JavaScript; }
+ bool isVerilog() const { return Language == LK_Verilog; }
+ bool isTextProto() const { return Language == LK_TextProto; }
+ bool isProto() const { return Language == LK_Proto || isTextProto(); }
+ bool isTableGen() const { return Language == LK_TableGen; }
+
+ /// The language that this format style targets.
+ /// \note
+ /// You can specify the language (``C``, ``Cpp``, or ``ObjC``) for ``.h``
+ /// files by adding a ``// clang-format Language:`` line before the first
+ /// non-comment (and non-empty) line, e.g. ``// clang-format Language: Cpp``.
+ /// \endnote
+ /// \version 3.5
+ LanguageKind Language;
+
+ /// Line ending style.
+ enum LineEndingStyle : int8_t {
+ /// Use ``\n``.
+ LE_LF,
+ /// Use ``\r\n``.
+ LE_CRLF,
+ /// Use ``\n`` unless the input has more lines ending in ``\r\n``.
+ LE_DeriveLF,
+ /// Use ``\r\n`` unless the input has more lines ending in ``\n``.
+ LE_DeriveCRLF,
+ };
+
+ /// Line ending style (``\n`` or ``\r\n``) to use.
+ /// \version 16
+ LineEndingStyle LineEnding;
+
+ /// A regular expression matching macros that start a block.
+ /// \code
+ /// # With:
+ /// MacroBlockBegin: "^NS_MAP_BEGIN|\
+ /// NS_TABLE_HEAD$"
+ /// MacroBlockEnd: "^\
+ /// NS_MAP_END|\
+ /// NS_TABLE_.*_END$"
+ ///
+ /// NS_MAP_BEGIN
+ /// foo();
+ /// NS_MAP_END
+ ///
+ /// NS_TABLE_HEAD
+ /// bar();
+ /// NS_TABLE_FOO_END
+ ///
+ /// # Without:
+ /// NS_MAP_BEGIN
+ /// foo();
+ /// NS_MAP_END
+ ///
+ /// NS_TABLE_HEAD
+ /// bar();
+ /// NS_TABLE_FOO_END
+ /// \endcode
+ /// \version 3.7
+ std::string MacroBlockBegin;
+
+ /// A regular expression matching macros that end a block.
+ /// \version 3.7
+ std::string MacroBlockEnd;
+
+ /// A list of macros of the form \c <definition>=<expansion> .
+ ///
+ /// Code will be parsed with macros expanded, in order to determine how to
+ /// interpret and format the macro arguments.
+ ///
+ /// For example, the code:
+ /// \code
+ /// A(a*b);
+ /// \endcode
+ ///
+ /// will usually be interpreted as a call to a function A, and the
+ /// multiplication expression will be formatted as ``a * b``.
+ ///
+ /// If we specify the macro definition:
+ /// \code{.yaml}
+ /// Macros:
+ /// - A(x)=x
+ /// \endcode
+ ///
+ /// the code will now be parsed as a declaration of the variable b of type a*,
+ /// and formatted as ``a* b`` (depending on pointer-binding rules).
+ ///
+ /// Features and restrictions:
+ /// * Both function-like macros and object-like macros are supported.
+ /// * Macro arguments must be used exactly once in the expansion.
+ /// * No recursive expansion; macros referencing other macros will be
+ /// ignored.
+ /// * Overloading by arity is supported: for example, given the macro
+ /// definitions A=x, A()=y, A(a)=a
+ ///
+ /// \code
+ /// A; -> x;
+ /// A(); -> y;
+ /// A(z); -> z;
+ /// A(a, b); // will not be expanded.
+ /// \endcode
+ ///
+ /// \version 17
+ std::vector<std::string> Macros;
+
+ /// A vector of function-like macros whose invocations should be skipped by
+ /// ``RemoveParentheses``.
+ /// \version 21
+ std::vector<std::string> MacrosSkippedByRemoveParentheses;
+
+ /// The maximum number of consecutive empty lines to keep.
+ /// \code
+ /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
+ /// int f() { int f() {
+ /// int = 1; int i = 1;
+ /// i = foo();
+ /// i = foo(); return i;
+ /// }
+ /// return i;
+ /// }
+ /// \endcode
+ /// \version 3.7
+ unsigned MaxEmptyLinesToKeep;
+
+ /// Different ways to indent namespace contents.
+ enum NamespaceIndentationKind : int8_t {
+ /// Don't indent in namespaces.
+ /// \code
+ /// namespace out {
+ /// int i;
+ /// namespace in {
+ /// int i;
+ /// }
+ /// }
+ /// \endcode
+ NI_None,
+ /// Indent only in inner namespaces (nested in other namespaces).
+ /// \code
+ /// namespace out {
+ /// int i;
+ /// namespace in {
+ /// int i;
+ /// }
+ /// }
+ /// \endcode
+ NI_Inner,
+ /// Indent in all namespaces.
+ /// \code
+ /// namespace out {
+ /// int i;
+ /// namespace in {
+ /// int i;
+ /// }
+ /// }
+ /// \endcode
+ NI_All
+ };
+
+ /// The indentation used for namespaces.
+ /// \version 3.7
+ NamespaceIndentationKind NamespaceIndentation;
+
+ /// A vector of macros which are used to open namespace blocks.
+ ///
+ /// These are expected to be macros of the form:
+ /// \code
+ /// NAMESPACE(<namespace-name>, ...) {
+ /// <namespace-content>
+ /// }
+ /// \endcode
+ ///
+ /// For example: TESTSUITE
+ /// \version 9
+ std::vector<std::string> NamespaceMacros;
+
+ /// Control over each component in a numeric literal.
+ enum NumericLiteralComponentStyle : int8_t {
+ /// Leave this component of the literal as is.
+ NLCS_Leave,
+ /// Format this component with uppercase characters.
+ NLCS_Upper,
+ /// Format this component with lowercase characters.
+ NLCS_Lower,
+ };
+
+ /// Separate control for each numeric literal component.
+ ///
+ /// For example, the config below will leave exponent letters alone, reformat
+ /// hexadecimal digits in lowercase, reformat numeric literal prefixes in
+ /// uppercase, and reformat suffixes in lowercase.
+ /// \code
+ /// NumericLiteralCase:
+ /// ExponentLetter: Leave
+ /// HexDigit: Lower
+ /// Prefix: Upper
+ /// Suffix: Lower
+ /// \endcode
+ struct NumericLiteralCaseStyle {
+ /// Format floating point exponent separator letter case.
+ /// \code
+ /// float a = 6.02e23 + 1.0E10; // Leave
+ /// float a = 6.02E23 + 1.0E10; // Upper
+ /// float a = 6.02e23 + 1.0e10; // Lower
+ /// \endcode
+ NumericLiteralComponentStyle ExponentLetter;
+ /// Format hexadecimal digit case.
+ /// \code
+ /// a = 0xaBcDeF; // Leave
+ /// a = 0xABCDEF; // Upper
+ /// a = 0xabcdef; // Lower
+ /// \endcode
+ NumericLiteralComponentStyle HexDigit;
+ /// Format integer prefix case.
+ /// \code
+ /// a = 0XF0 | 0b1; // Leave
+ /// a = 0XF0 | 0B1; // Upper
+ /// a = 0xF0 | 0b1; // Lower
+ /// \endcode
+ NumericLiteralComponentStyle Prefix;
+ /// Format suffix case. This option excludes case-sensitive reserved
+ /// suffixes, such as ``min`` in C++.
+ /// \code
+ /// a = 1uLL; // Leave
+ /// a = 1ULL; // Upper
+ /// a = 1ull; // Lower
+ /// \endcode
+ NumericLiteralComponentStyle Suffix;
+
+ bool operator==(const NumericLiteralCaseStyle &R) const {
+ return ExponentLetter == R.ExponentLetter && HexDigit == R.HexDigit &&
+ Prefix == R.Prefix && Suffix == R.Suffix;
+ }
+
+ bool operator!=(const NumericLiteralCaseStyle &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Capitalization style for numeric literals.
+ /// \version 22
+ NumericLiteralCaseStyle NumericLiteralCase;
+
+ /// Controls bin-packing Objective-C protocol conformance list
+ /// items into as few lines as possible when they go over ``ColumnLimit``.
+ ///
+ /// If ``Auto`` (the default), delegates to the value in
+ /// ``BinPackParameters``. If that is ``BinPack``, bin-packs Objective-C
+ /// protocol conformance list items into as few lines as possible
+ /// whenever they go over ``ColumnLimit``.
+ ///
+ /// If ``Always``, always bin-packs Objective-C protocol conformance
+ /// list items into as few lines as possible whenever they go over
+ /// ``ColumnLimit``.
+ ///
+ /// If ``Never``, lays out Objective-C protocol conformance list items
+ /// onto individual lines whenever they go over ``ColumnLimit``.
+ ///
+ /// \code{.objc}
+ /// Always (or Auto, if BinPackParameters==BinPack):
+ /// @interface ccccccccccccc () <
+ /// ccccccccccccc, ccccccccccccc,
+ /// ccccccccccccc, ccccccccccccc> {
+ /// }
+ ///
+ /// Never (or Auto, if BinPackParameters!=BinPack):
+ /// @interface ddddddddddddd () <
+ /// ddddddddddddd,
+ /// ddddddddddddd,
+ /// ddddddddddddd,
+ /// ddddddddddddd> {
+ /// }
+ /// \endcode
+ /// \version 7
+ BinPackStyle ObjCBinPackProtocolList;
+
+ /// The number of characters to use for indentation of ObjC blocks.
+ /// \code{.objc}
+ /// ObjCBlockIndentWidth: 4
+ ///
+ /// [operation setCompletionBlock:^{
+ /// [self onOperationDone];
+ /// }];
+ /// \endcode
+ /// \version 3.7
+ unsigned ObjCBlockIndentWidth;
+
+ /// Break parameters list into lines when there is nested block
+ /// parameters in a function call.
+ /// \code
+ /// false:
+ /// - (void)_aMethod
+ /// {
+ /// [self.test1 t:self w:self callback:^(typeof(self) self, NSNumber
+ /// *u, NSNumber *v) {
+ /// u = c;
+ /// }]
+ /// }
+ /// true:
+ /// - (void)_aMethod
+ /// {
+ /// [self.test1 t:self
+ /// w:self
+ /// callback:^(typeof(self) self, NSNumber *u, NSNumber *v) {
+ /// u = c;
+ /// }]
+ /// }
+ /// \endcode
+ /// \version 11
+ bool ObjCBreakBeforeNestedBlockParam;
+
+ /// The order in which ObjC property attributes should appear.
+ ///
+ /// Attributes in code will be sorted in the order specified. Any attributes
+ /// encountered that are not mentioned in this array will be sorted last, in
+ /// stable order. Comments between attributes will leave the attributes
+ /// untouched.
+ /// \warning
+ /// Using this option could lead to incorrect code formatting due to
+ /// clang-format's lack of complete semantic information. As such, extra
+ /// care should be taken to review code changes made by this option.
+ /// \endwarning
+ /// \code{.yaml}
+ /// ObjCPropertyAttributeOrder: [
+ /// class, direct,
+ /// atomic, nonatomic,
+ /// assign, retain, strong, copy, weak, unsafe_unretained,
+ /// readonly, readwrite, getter, setter,
+ /// nullable, nonnull, null_resettable, null_unspecified
+ /// ]
+ /// \endcode
+ /// \version 18
+ std::vector<std::string> ObjCPropertyAttributeOrder;
+
+ /// Add or remove a space between the '-'/'+' and the return type in
+ /// Objective-C method declarations. i.e
+ /// \code{.objc}
+ /// false: true:
+ ///
+ /// -(void)method vs. - (void)method
+ /// \endcode
+ /// \version 23
+ bool ObjCSpaceAfterMethodDeclarationPrefix;
+
+ /// Add a space after ``@property`` in Objective-C, i.e. use
+ /// ``@property (readonly)`` instead of ``@property(readonly)``.
+ /// \version 3.7
+ bool ObjCSpaceAfterProperty;
+
+ /// Add a space in front of an Objective-C protocol list, i.e. use
+ /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
+ /// \version 3.7
+ bool ObjCSpaceBeforeProtocolList;
+
+ /// A regular expression that describes markers for turning formatting off for
+ /// one line. If it matches a comment that is the only token of a line,
+ /// clang-format skips the comment and the next line. Otherwise, clang-format
+ /// skips lines containing a matched token.
+ /// \note
+ /// This option does not apply to ``IntegerLiteralSeparator`` and
+ /// ``NumericLiteralCase``.
+ /// \endnote
+ /// \code
+ /// // OneLineFormatOffRegex: ^(// NOLINT|logger$)
+ /// // results in the output below:
+ /// int a;
+ /// int b ; // NOLINT
+ /// int c;
+ /// // NOLINTNEXTLINE
+ /// int d ;
+ /// int e;
+ /// s = "// NOLINT";
+ /// logger() ;
+ /// logger2();
+ /// my_logger();
+ /// \endcode
+ /// \version 21
+ std::string OneLineFormatOffRegex;
+
+ /// Different ways to try to fit all constructor initializers on a line.
+ enum PackConstructorInitializersStyle : int8_t {
+ /// Always put each constructor initializer on its own line.
+ /// \code
+ /// Constructor()
+ /// : a(),
+ /// b()
+ /// \endcode
+ PCIS_Never,
+ /// Bin-pack constructor initializers.
+ /// \code
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(),
+ /// cccccccccccccccccccc()
+ /// \endcode
+ PCIS_BinPack,
+ /// Put all constructor initializers on the current line if they fit.
+ /// Otherwise, put each one on its own line.
+ /// \code
+ /// Constructor() : a(), b()
+ ///
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(),
+ /// bbbbbbbbbbbbbbbbbbbb(),
+ /// ddddddddddddd()
+ /// \endcode
+ PCIS_CurrentLine,
+ /// Same as ``PCIS_CurrentLine`` except that if all constructor initializers
+ /// do not fit on the current line, try to fit them on the next line.
+ /// \code
+ /// Constructor() : a(), b()
+ ///
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()
+ ///
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(),
+ /// bbbbbbbbbbbbbbbbbbbb(),
+ /// cccccccccccccccccccc()
+ /// \endcode
+ PCIS_NextLine,
+ /// Put all constructor initializers on the next line if they fit.
+ /// Otherwise, put each one on its own line.
+ /// \code
+ /// Constructor()
+ /// : a(), b()
+ ///
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()
+ ///
+ /// Constructor()
+ /// : aaaaaaaaaaaaaaaaaaaa(),
+ /// bbbbbbbbbbbbbbbbbbbb(),
+ /// cccccccccccccccccccc()
+ /// \endcode
+ PCIS_NextLineOnly,
+ };
+
+ /// The pack constructor initializers style to use.
+ /// \version 14
+ PackConstructorInitializersStyle PackConstructorInitializers;
+
+ /// The penalty for breaking around an assignment operator.
+ /// \version 5
+ unsigned PenaltyBreakAssignment;
+
+ /// The penalty for breaking a function call after ``call(``.
+ /// \version 3.7
+ unsigned PenaltyBreakBeforeFirstCallParameter;
+
+ /// The penalty for breaking before a member access operator (``.``, ``->``).
+ /// \version 20
+ unsigned PenaltyBreakBeforeMemberAccess;
+
+ /// The penalty for each line break introduced inside a comment.
+ /// \version 3.7
+ unsigned PenaltyBreakComment;
+
+ /// The penalty for breaking before the first ``<<``.
+ /// \version 3.7
+ unsigned PenaltyBreakFirstLessLess;
+
+ /// The penalty for breaking after ``(``.
+ /// \version 14
+ unsigned PenaltyBreakOpenParenthesis;
+
+ /// The penalty for breaking after ``::``.
+ /// \version 18
+ unsigned PenaltyBreakScopeResolution;
+
+ /// The penalty for each line break introduced inside a string literal.
+ /// \version 3.7
+ unsigned PenaltyBreakString;
+
+ /// The penalty for breaking after template declaration.
+ /// \version 7
+ unsigned PenaltyBreakTemplateDeclaration;
+
+ /// The penalty for each character outside of the column limit.
+ /// \version 3.7
+ unsigned PenaltyExcessCharacter;
+
+ /// Penalty for each character of whitespace indentation
+ /// (counted relative to leading non-whitespace column).
+ /// \version 12
+ unsigned PenaltyIndentedWhitespace;
+
+ /// Penalty for putting the return type of a function onto its own line.
+ /// \version 3.7
+ unsigned PenaltyReturnTypeOnItsOwnLine;
+
+ /// The ``&``, ``&&`` and ``*`` alignment style.
+ enum PointerAlignmentStyle : int8_t {
+ /// Align pointer to the left.
+ /// \code
+ /// int* a;
+ /// \endcode
+ PAS_Left,
+ /// Align pointer to the right.
+ /// \code
+ /// int *a;
+ /// \endcode
+ PAS_Right,
+ /// Align pointer in the middle.
+ /// \code
+ /// int * a;
+ /// \endcode
+ PAS_Middle
+ };
+
+ /// Pointer and reference alignment style.
+ /// \version 3.7
+ PointerAlignmentStyle PointerAlignment;
+
+ /// The number of columns to use for indentation of preprocessor statements.
+ /// When set to -1 (default) ``IndentWidth`` is used also for preprocessor
+ /// statements.
+ /// \code
+ /// PPIndentWidth: 1
+ ///
+ /// #ifdef __linux__
+ /// # define FOO
+ /// #else
+ /// # define BAR
+ /// #endif
+ /// \endcode
+ /// \version 13
+ int PPIndentWidth;
+
+ /// Different specifiers and qualifiers alignment styles.
+ enum QualifierAlignmentStyle : int8_t {
+ /// Don't change specifiers/qualifiers to either Left or Right alignment
+ /// (default).
+ /// \code
+ /// int const a;
+ /// const int *a;
+ /// \endcode
+ QAS_Leave,
+ /// Change specifiers/qualifiers to be left-aligned.
+ /// \code
+ /// const int a;
+ /// const int *a;
+ /// \endcode
+ QAS_Left,
+ /// Change specifiers/qualifiers to be right-aligned.
+ /// \code
+ /// int const a;
+ /// int const *a;
+ /// \endcode
+ QAS_Right,
+ /// Change specifiers/qualifiers to be aligned based on ``QualifierOrder``.
+ /// With:
+ /// \code{.yaml}
+ /// QualifierOrder: [inline, static, type, const]
+ /// \endcode
+ ///
+ /// \code
+ ///
+ /// int const a;
+ /// int const *a;
+ /// \endcode
+ QAS_Custom
+ };
+
+ /// Different ways to arrange specifiers and qualifiers (e.g. const/volatile).
+ /// \warning
+ /// Setting ``QualifierAlignment`` to something other than ``Leave``, COULD
+ /// lead to incorrect code formatting due to incorrect decisions made due to
+ /// clang-formats lack of complete semantic information.
+ /// As such extra care should be taken to review code changes made by the use
+ /// of this option.
+ /// \endwarning
+ /// \version 14
+ QualifierAlignmentStyle QualifierAlignment;
+
+ /// The order in which the qualifiers appear.
+ /// The order is an array that can contain any of the following:
+ ///
+ /// * ``const``
+ /// * ``inline``
+ /// * ``static``
+ /// * ``friend``
+ /// * ``constexpr``
+ /// * ``volatile``
+ /// * ``restrict``
+ /// * ``type``
+ ///
+ /// \note
+ /// It must contain ``type``.
+ /// \endnote
+ ///
+ /// Items to the left of ``type`` will be placed to the left of the type and
+ /// aligned in the order supplied. Items to the right of ``type`` will be
+ /// placed to the right of the type and aligned in the order supplied.
+ ///
+ /// \code{.yaml}
+ /// QualifierOrder: [inline, static, type, const, volatile]
+ /// \endcode
+ /// \version 14
+ std::vector<std::string> QualifierOrder;
+
+ /// See documentation of ``RawStringFormats``.
+ struct RawStringFormat {
+ /// The language of this raw string.
+ LanguageKind Language;
+ /// A list of raw string delimiters that match this language.
+ std::vector<std::string> Delimiters;
+ /// A list of enclosing function names that match this language.
+ std::vector<std::string> EnclosingFunctions;
+ /// The canonical delimiter for this language.
+ std::string CanonicalDelimiter;
+ /// The style name on which this raw string format is based on.
+ /// If not specified, the raw string format is based on the style that this
+ /// format is based on.
+ std::string BasedOnStyle;
+ bool operator==(const RawStringFormat &Other) const {
+ return Language == Other.Language && Delimiters == Other.Delimiters &&
+ EnclosingFunctions == Other.EnclosingFunctions &&
+ CanonicalDelimiter == Other.CanonicalDelimiter &&
+ BasedOnStyle == Other.BasedOnStyle;
+ }
+ };
+
+ /// Defines hints for detecting supported languages code blocks in raw
+ /// strings.
+ ///
+ /// A raw string with a matching delimiter or a matching enclosing function
+ /// name will be reformatted assuming the specified language based on the
+ /// style for that language defined in the .clang-format file. If no style has
+ /// been defined in the .clang-format file for the specific language, a
+ /// predefined style given by ``BasedOnStyle`` is used. If ``BasedOnStyle`` is
+ /// not found, the formatting is based on ``LLVM`` style. A matching delimiter
+ /// takes precedence over a matching enclosing function name for determining
+ /// the language of the raw string contents.
+ ///
+ /// If a canonical delimiter is specified, occurrences of other delimiters for
+ /// the same language will be updated to the canonical if possible.
+ ///
+ /// There should be at most one specification per language and each delimiter
+ /// and enclosing function should not occur in multiple specifications.
+ ///
+ /// To configure this in the .clang-format file, use:
+ /// \code{.yaml}
+ /// RawStringFormats:
+ /// - Language: TextProto
+ /// Delimiters:
+ /// - pb
+ /// - proto
+ /// EnclosingFunctions:
+ /// - PARSE_TEXT_PROTO
+ /// BasedOnStyle: google
+ /// - Language: Cpp
+ /// Delimiters:
+ /// - cc
+ /// - cpp
+ /// BasedOnStyle: LLVM
+ /// CanonicalDelimiter: cc
+ /// \endcode
+ /// \version 6
+ std::vector<RawStringFormat> RawStringFormats;
+
+ /// The ``&`` and ``&&`` alignment style.
+ enum ReferenceAlignmentStyle : int8_t {
+ /// Align reference like ``PointerAlignment``.
+ RAS_Pointer,
+ /// Align reference to the left.
+ /// \code
+ /// int& a;
+ /// \endcode
+ RAS_Left,
+ /// Align reference to the right.
+ /// \code
+ /// int &a;
+ /// \endcode
+ RAS_Right,
+ /// Align reference in the middle.
+ /// \code
+ /// int & a;
+ /// \endcode
+ RAS_Middle
+ };
+
+ /// Reference alignment style (overrides ``PointerAlignment`` for references).
+ /// \version 13
+ ReferenceAlignmentStyle ReferenceAlignment;
+
+ // clang-format off
+ /// Types of comment reflow style.
+ enum ReflowCommentsStyle : int8_t {
+ /// Leave comments untouched.
+ /// \code
+ /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
+ /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
+ /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
+ /// * and a misaligned second line */
+ /// \endcode
+ RCS_Never,
+ /// Only apply indentation rules, moving comments left or right, without
+ /// changing formatting inside the comments.
+ /// \code
+ /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
+ /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
+ /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
+ /// * and a misaligned second line */
+ /// \endcode
+ RCS_IndentOnly,
+ /// Apply indentation rules and reflow long comments into new lines, trying
+ /// to obey the ``ColumnLimit``.
+ /// \code
+ /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
+ /// // information
+ /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
+ /// * information */
+ /// /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
+ /// * information and a misaligned second line */
+ /// \endcode
+ RCS_Always
+ };
+ // clang-format on
+
+ /// Comment reformatting style.
+ /// \version 3.8
+ ReflowCommentsStyle ReflowComments;
+
+ /// Remove optional braces of control statements (``if``, ``else``, ``for``,
+ /// and ``while``) in C++ according to the LLVM coding style.
+ /// \warning
+ /// This option will be renamed and expanded to support other styles.
+ /// \endwarning
+ /// \warning
+ /// Setting this option to ``true`` could lead to incorrect code formatting
+ /// due to clang-format's lack of complete semantic information. As such,
+ /// extra care should be taken to review code changes made by this option.
+ /// \endwarning
+ /// \code
+ /// false: true:
+ ///
+ /// if (isa<FunctionDecl>(D)) { vs. if (isa<FunctionDecl>(D))
+ /// handleFunctionDecl(D); handleFunctionDecl(D);
+ /// } else if (isa<VarDecl>(D)) { else if (isa<VarDecl>(D))
+ /// handleVarDecl(D); handleVarDecl(D);
+ /// }
+ ///
+ /// if (isa<VarDecl>(D)) { vs. if (isa<VarDecl>(D)) {
+ /// for (auto *A : D.attrs()) { for (auto *A : D.attrs())
+ /// if (shouldProcessAttr(A)) { if (shouldProcessAttr(A))
+ /// handleAttr(A); handleAttr(A);
+ /// } }
+ /// }
+ /// }
+ ///
+ /// if (isa<FunctionDecl>(D)) { vs. if (isa<FunctionDecl>(D))
+ /// for (auto *A : D.attrs()) { for (auto *A : D.attrs())
+ /// handleAttr(A); handleAttr(A);
+ /// }
+ /// }
+ ///
+ /// if (auto *D = (T)(D)) { vs. if (auto *D = (T)(D)) {
+ /// if (shouldProcess(D)) { if (shouldProcess(D))
+ /// handleVarDecl(D); handleVarDecl(D);
+ /// } else { else
+ /// markAsIgnored(D); markAsIgnored(D);
+ /// } }
+ /// }
+ ///
+ /// if (a) { vs. if (a)
+ /// b(); b();
+ /// } else { else if (c)
+ /// if (c) { d();
+ /// d(); else
+ /// } else { e();
+ /// e();
+ /// }
+ /// }
+ /// \endcode
+ /// \version 14
+ bool RemoveBracesLLVM;
+
+ /// Remove empty lines within unwrapped lines.
+ /// \code
+ /// false: true:
+ ///
+ /// int c vs. int c = a + b;
+ ///
+ /// = a + b;
+ ///
+ /// enum : unsigned vs. enum : unsigned {
+ /// AA = 0,
+ /// { BB
+ /// AA = 0, } myEnum;
+ /// BB
+ /// } myEnum;
+ ///
+ /// while ( vs. while (true) {
+ /// }
+ /// true) {
+ /// }
+ /// \endcode
+ /// \version 20
+ bool RemoveEmptyLinesInUnwrappedLines;
+
+ /// Types of redundant parentheses to remove.
+ enum RemoveParenthesesStyle : int8_t {
+ /// Do not remove parentheses.
+ /// \code
+ /// class __declspec((dllimport)) X {};
+ /// co_return (((0)));
+ /// return ((a + b) - ((c + d)));
+ /// \endcode
+ RPS_Leave,
+ /// Replace multiple parentheses with single parentheses.
+ /// \code
+ /// class __declspec(dllimport) X {};
+ /// co_return (0);
+ /// return ((a + b) - (c + d));
+ /// \endcode
+ RPS_MultipleParentheses,
+ /// Also remove parentheses enclosing the expression in a
+ /// ``return``/``co_return`` statement.
+ /// \code
+ /// class __declspec(dllimport) X {};
+ /// co_return 0;
+ /// return (a + b) - (c + d);
+ /// \endcode
+ RPS_ReturnStatement,
+ };
+
+ /// Remove redundant parentheses.
+ /// \warning
+ /// Setting this option to any value other than ``Leave`` could lead to
+ /// incorrect code formatting due to clang-format's lack of complete semantic
+ /// information. As such, extra care should be taken to review code changes
+ /// made by this option.
+ /// \endwarning
+ /// \version 17
+ RemoveParenthesesStyle RemoveParentheses;
+
+ /// Remove semicolons after the closing braces of functions and
+ /// constructors/destructors.
+ /// \warning
+ /// Setting this option to ``true`` could lead to incorrect code formatting
+ /// due to clang-format's lack of complete semantic information. As such,
+ /// extra care should be taken to review code changes made by this option.
+ /// \endwarning
+ /// \code
+ /// false: true:
+ ///
+ /// int max(int a, int b) { int max(int a, int b) {
+ /// return a > b ? a : b; return a > b ? a : b;
+ /// }; }
+ ///
+ /// \endcode
+ /// \version 16
+ bool RemoveSemicolon;
+
+ /// The possible positions for the requires clause. The ``IndentRequires``
+ /// option is only used if the ``requires`` is put on the start of a line.
+ enum RequiresClausePositionStyle : int8_t {
+ /// Always put the ``requires`` clause on its own line (possibly followed by
+ /// a semicolon).
+ /// \code
+ /// template <typename T>
+ /// requires C<T>
+ /// struct Foo {...
+ ///
+ /// template <typename T>
+ /// void bar(T t)
+ /// requires C<T>;
+ ///
+ /// template <typename T>
+ /// requires C<T>
+ /// void bar(T t) {...
+ ///
+ /// template <typename T>
+ /// void baz(T t)
+ /// requires C<T>
+ /// {...
+ /// \endcode
+ RCPS_OwnLine,
+ /// As with ``OwnLine``, except, unless otherwise prohibited, place a
+ /// following open brace (of a function definition) to follow on the same
+ /// line.
+ /// \code
+ /// void bar(T t)
+ /// requires C<T> {
+ /// return;
+ /// }
+ ///
+ /// void bar(T t)
+ /// requires C<T> {}
+ ///
+ /// template <typename T>
+ /// requires C<T>
+ /// void baz(T t) {
+ /// ...
+ /// \endcode
+ RCPS_OwnLineWithBrace,
+ /// Try to put the clause together with the preceding part of a declaration.
+ /// For class templates: stick to the template declaration.
+ /// For function templates: stick to the template declaration.
+ /// For function declaration followed by a requires clause: stick to the
+ /// parameter list.
+ /// \code
+ /// template <typename T> requires C<T>
+ /// struct Foo {...
+ ///
+ /// template <typename T> requires C<T>
+ /// void bar(T t) {...
+ ///
+ /// template <typename T>
+ /// void baz(T t) requires C<T>
+ /// {...
+ /// \endcode
+ RCPS_WithPreceding,
+ /// Try to put the ``requires`` clause together with the class or function
+ /// declaration.
+ /// \code
+ /// template <typename T>
+ /// requires C<T> struct Foo {...
+ ///
+ /// template <typename T>
+ /// requires C<T> void bar(T t) {...
+ ///
+ /// template <typename T>
+ /// void baz(T t)
+ /// requires C<T> {...
+ /// \endcode
+ RCPS_WithFollowing,
+ /// Try to put everything in the same line if possible. Otherwise normal
+ /// line breaking rules take over.
+ /// \code
+ /// // Fitting:
+ /// template <typename T> requires C<T> struct Foo {...
+ ///
+ /// template <typename T> requires C<T> void bar(T t) {...
+ ///
+ /// template <typename T> void bar(T t) requires C<T> {...
+ ///
+ /// // Not fitting, one possible example:
+ /// template <typename LongName>
+ /// requires C<LongName>
+ /// struct Foo {...
+ ///
+ /// template <typename LongName>
+ /// requires C<LongName>
+ /// void bar(LongName ln) {
+ ///
+ /// template <typename LongName>
+ /// void bar(LongName ln)
+ /// requires C<LongName> {
+ /// \endcode
+ RCPS_SingleLine,
+ };
+
+ /// The position of the ``requires`` clause.
+ /// \version 15
+ RequiresClausePositionStyle RequiresClausePosition;
+
+ /// Indentation logic for requires expression bodies.
+ enum RequiresExpressionIndentationKind : int8_t {
+ /// Align requires expression body relative to the indentation level of the
+ /// outer scope the requires expression resides in.
+ /// This is the default.
+ /// \code
+ /// template <typename T>
+ /// concept C = requires(T t) {
+ /// ...
+ /// }
+ /// \endcode
+ REI_OuterScope,
+ /// Align requires expression body relative to the ``requires`` keyword.
+ /// \code
+ /// template <typename T>
+ /// concept C = requires(T t) {
+ /// ...
+ /// }
+ /// \endcode
+ REI_Keyword,
+ };
+
+ /// The indentation used for requires expression bodies.
+ /// \version 16
+ RequiresExpressionIndentationKind RequiresExpressionIndentation;
+
+ /// The style if definition blocks should be separated.
+ enum SeparateDefinitionStyle : int8_t {
+ /// Leave definition blocks as they are.
+ SDS_Leave,
+ /// Insert an empty line between definition blocks.
+ SDS_Always,
+ /// Remove any empty line between definition blocks.
+ SDS_Never
+ };
+
+ /// Specifies the use of empty lines to separate definition blocks, including
+ /// classes, structs, enums, and functions.
+ /// \code
+ /// Never v.s. Always
+ /// #include <cstring> #include <cstring>
+ /// struct Foo {
+ /// int a, b, c; struct Foo {
+ /// }; int a, b, c;
+ /// namespace Ns { };
+ /// class Bar {
+ /// public: namespace Ns {
+ /// struct Foobar { class Bar {
+ /// int a; public:
+ /// int b; struct Foobar {
+ /// }; int a;
+ /// private: int b;
+ /// int t; };
+ /// int method1() {
+ /// // ... private:
+ /// } int t;
+ /// enum List {
+ /// ITEM1, int method1() {
+ /// ITEM2 // ...
+ /// }; }
+ /// template<typename T>
+ /// int method2(T x) { enum List {
+ /// // ... ITEM1,
+ /// } ITEM2
+ /// int i, j, k; };
+ /// int method3(int par) {
+ /// // ... template<typename T>
+ /// } int method2(T x) {
+ /// }; // ...
+ /// class C {}; }
+ /// }
+ /// int i, j, k;
+ ///
+ /// int method3(int par) {
+ /// // ...
+ /// }
+ /// };
+ ///
+ /// class C {};
+ /// }
+ /// \endcode
+ /// \version 14
+ SeparateDefinitionStyle SeparateDefinitionBlocks;
+
+ /// The maximal number of unwrapped lines that a short namespace spans.
+ /// Defaults to 1.
+ ///
+ /// This determines the maximum length of short namespaces by counting
+ /// unwrapped lines (i.e. containing neither opening nor closing
+ /// namespace brace) and makes ``FixNamespaceComments`` omit adding
+ /// end comments for those.
+ /// \code
+ /// ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0
+ /// namespace a { namespace a {
+ /// int foo; int foo;
+ /// } } // namespace a
+ ///
+ /// ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0
+ /// namespace b { namespace b {
+ /// int foo; int foo;
+ /// int bar; int bar;
+ /// } // namespace b } // namespace b
+ /// \endcode
+ /// \version 13
+ unsigned ShortNamespaceLines;
+
+ /// Do not format macro definition body.
+ /// \version 18
+ bool SkipMacroDefinitionBody;
+
+ /// Includes sorting options.
+ struct SortIncludesOptions {
+ /// If ``true``, includes are sorted based on the other suboptions below.
+ /// (``Never`` is deprecated by ``Enabled: false``.)
+ bool Enabled;
+ /// Whether or not includes are sorted in a case-insensitive fashion.
+ /// (``CaseSensitive`` and ``CaseInsensitive`` are deprecated by
+ /// ``IgnoreCase: false`` and ``IgnoreCase: true``, respectively.)
+ /// \code
+ /// true: false:
+ /// #include "A/B.h" vs. #include "A/B.h"
+ /// #include "A/b.h" #include "A/b.h"
+ /// #include "a/b.h" #include "B/A.h"
+ /// #include "B/A.h" #include "B/a.h"
+ /// #include "B/a.h" #include "a/b.h"
+ /// \endcode
+ bool IgnoreCase;
+ /// When sorting includes in each block, only take file extensions into
+ /// account if two includes compare equal otherwise.
+ /// \code
+ /// true: false:
+ /// # include "A.h" vs. # include "A-util.h"
+ /// # include "A.inc" # include "A.h"
+ /// # include "A-util.h" # include "A.inc"
+ /// \endcode
+ bool IgnoreExtension;
+ bool operator==(const SortIncludesOptions &R) const {
+ return Enabled == R.Enabled && IgnoreCase == R.IgnoreCase &&
+ IgnoreExtension == R.IgnoreExtension;
+ }
+ bool operator!=(const SortIncludesOptions &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Controls if and how clang-format will sort ``#includes``.
+ /// \version 3.8
+ SortIncludesOptions SortIncludes;
+
+ /// Position for Java Static imports.
+ enum SortJavaStaticImportOptions : int8_t {
+ /// Static imports are placed before non-static imports.
+ /// \code{.java}
+ /// import static org.example.function1;
+ ///
+ /// import org.example.ClassA;
+ /// \endcode
+ SJSIO_Before,
+ /// Static imports are placed after non-static imports.
+ /// \code{.java}
+ /// import org.example.ClassA;
+ ///
+ /// import static org.example.function1;
+ /// \endcode
+ SJSIO_After,
+ };
+
+ /// When sorting Java imports, by default static imports are placed before
+ /// non-static imports. If ``JavaStaticImportAfterImport`` is ``After``,
+ /// static imports are placed after non-static imports.
+ /// \version 12
+ SortJavaStaticImportOptions SortJavaStaticImport;
+
+ /// Using declaration sorting options.
+ enum SortUsingDeclarationsOptions : int8_t {
+ /// Using declarations are never sorted.
+ /// \code
+ /// using std::chrono::duration_cast;
+ /// using std::move;
+ /// using boost::regex;
+ /// using boost::regex_constants::icase;
+ /// using std::string;
+ /// \endcode
+ SUD_Never,
+ /// Using declarations are sorted in the order defined as follows:
+ /// Split the strings by ``::`` and discard any initial empty strings. Sort
+ /// the lists of names lexicographically, and within those groups, names are
+ /// in case-insensitive lexicographic order.
+ /// \code
+ /// using boost::regex;
+ /// using boost::regex_constants::icase;
+ /// using std::chrono::duration_cast;
+ /// using std::move;
+ /// using std::string;
+ /// \endcode
+ SUD_Lexicographic,
+ /// Using declarations are sorted in the order defined as follows:
+ /// Split the strings by ``::`` and discard any initial empty strings. The
+ /// last element of each list is a non-namespace name; all others are
+ /// namespace names. Sort the lists of names lexicographically, where the
+ /// sort order of individual names is that all non-namespace names come
+ /// before all namespace names, and within those groups, names are in
+ /// case-insensitive lexicographic order.
+ /// \code
+ /// using boost::regex;
+ /// using boost::regex_constants::icase;
+ /// using std::move;
+ /// using std::string;
+ /// using std::chrono::duration_cast;
+ /// \endcode
+ SUD_LexicographicNumeric,
+ };
+
+ /// Controls if and how clang-format will sort using declarations.
+ /// \version 5
+ SortUsingDeclarationsOptions SortUsingDeclarations;
+
+ /// If ``true``, a space is inserted after C style casts.
+ /// \code
+ /// true: false:
+ /// (int) i; vs. (int)i;
+ /// \endcode
+ /// \version 3.5
+ bool SpaceAfterCStyleCast;
+
+ /// If ``true``, a space is inserted after the logical not operator (``!``).
+ /// \code
+ /// true: false:
+ /// ! someExpression(); vs. !someExpression();
+ /// \endcode
+ /// \version 9
+ bool SpaceAfterLogicalNot;
+
+ /// If ``true``, a space will be inserted after the ``operator`` keyword.
+ /// \code
+ /// true: false:
+ /// bool operator ==(int a); vs. bool operator==(int a);
+ /// \endcode
+ /// \version 21
+ bool SpaceAfterOperatorKeyword;
+
+ /// If \c true, a space will be inserted after the ``template`` keyword.
+ /// \code
+ /// true: false:
+ /// template <int> void foo(); vs. template<int> void foo();
+ /// \endcode
+ /// \version 4
+ bool SpaceAfterTemplateKeyword;
+
+ /// Different ways to put a space before opening parentheses.
+ enum SpaceAroundPointerQualifiersStyle : int8_t {
+ /// Don't ensure spaces around pointer qualifiers and use PointerAlignment
+ /// instead.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const* x = NULL; vs. void *const *x = NULL;
+ /// \endcode
+ SAPQ_Default,
+ /// Ensure that there is a space before pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const* x = NULL; vs. void * const *x = NULL;
+ /// \endcode
+ SAPQ_Before,
+ /// Ensure that there is a space after pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const * x = NULL; vs. void *const *x = NULL;
+ /// \endcode
+ SAPQ_After,
+ /// Ensure that there is a space both before and after pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const * x = NULL; vs. void * const *x = NULL;
+ /// \endcode
+ SAPQ_Both,
+ };
+
+ /// Defines in which cases to put a space before or after pointer qualifiers
+ /// \version 12
+ SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers;
+
+ /// If ``false``, spaces will be removed before assignment operators.
+ /// \code
+ /// true: false:
+ /// int a = 5; vs. int a= 5;
+ /// a += 42; a+= 42;
+ /// \endcode
+ /// \version 3.7
+ bool SpaceBeforeAssignmentOperators;
+
+ /// If ``false``, spaces will be removed before case colon.
+ /// \code
+ /// true: false
+ /// switch (x) { vs. switch (x) {
+ /// case 1 : break; case 1: break;
+ /// } }
+ /// \endcode
+ /// \version 12
+ bool SpaceBeforeCaseColon;
+
+ /// If ``true``, a space will be inserted before a C++11 braced list
+ /// used to initialize an object (after the preceding identifier or type).
+ /// \code
+ /// true: false:
+ /// Foo foo { bar }; vs. Foo foo{ bar };
+ /// Foo {}; Foo{};
+ /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
+ /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
+ /// \endcode
+ /// \version 7
+ bool SpaceBeforeCpp11BracedList;
+
+ /// If ``false``, spaces will be removed before constructor initializer
+ /// colon.
+ /// \code
+ /// true: false:
+ /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
+ /// \endcode
+ /// \version 7
+ bool SpaceBeforeCtorInitializerColon;
+
+ /// If ``false``, spaces will be removed before inheritance colon.
+ /// \code
+ /// true: false:
+ /// class Foo : Bar {} vs. class Foo: Bar {}
+ /// \endcode
+ /// \version 7
+ bool SpaceBeforeInheritanceColon;
+
+ /// If ``true``, a space will be added before a JSON colon. For other
+ /// languages, e.g. JavaScript, use ``SpacesInContainerLiterals`` instead.
+ /// \code
+ /// true: false:
+ /// { {
+ /// "key" : "value" vs. "key": "value"
+ /// } }
+ /// \endcode
+ /// \version 17
+ bool SpaceBeforeJsonColon;
+
+ /// Different ways to put a space before opening parentheses.
+ enum SpaceBeforeParensStyle : int8_t {
+ /// This is **deprecated** and replaced by ``Custom`` below, with all
+ /// ``SpaceBeforeParensOptions`` but ``AfterPlacementOperator`` set to
+ /// ``false``.
+ SBPO_Never,
+ /// Put a space before opening parentheses only after control statement
+ /// keywords (``for/if/while...``).
+ /// \code
+ /// void f() {
+ /// if (true) {
+ /// f();
+ /// }
+ /// }
+ /// \endcode
+ SBPO_ControlStatements,
+ /// Same as ``SBPO_ControlStatements`` except this option doesn't apply to
+ /// ForEach and If macros. This is useful in projects where ForEach/If
+ /// macros are treated as function calls instead of control statements.
+ /// ``SBPO_ControlStatementsExceptForEachMacros`` remains an alias for
+ /// backward compatibility.
+ /// \code
+ /// void f() {
+ /// Q_FOREACH(...) {
+ /// f();
+ /// }
+ /// }
+ /// \endcode
+ SBPO_ControlStatementsExceptControlMacros,
+ /// Put a space before opening parentheses only if the parentheses are not
+ /// empty.
+ /// \code
+ /// void() {
+ /// if (true) {
+ /// f();
+ /// g (x, y, z);
+ /// }
+ /// }
+ /// \endcode
+ SBPO_NonEmptyParentheses,
+ /// Always put a space before opening parentheses, except when it's
+ /// prohibited by the syntax rules (in function-like macro definitions) or
+ /// when determined by other style rules (after unary operators, opening
+ /// parentheses, etc.)
+ /// \code
+ /// void f () {
+ /// if (true) {
+ /// f ();
+ /// }
+ /// }
+ /// \endcode
+ SBPO_Always,
+ /// Configure each individual space before parentheses in
+ /// ``SpaceBeforeParensOptions``.
+ SBPO_Custom,
+ };
+
+ /// Defines in which cases to put a space before opening parentheses.
+ /// \version 3.5
+ SpaceBeforeParensStyle SpaceBeforeParens;
+
+ /// Precise control over the spacing before parentheses.
+ /// \code
+ /// # Should be declared this way:
+ /// SpaceBeforeParens: Custom
+ /// SpaceBeforeParensOptions:
+ /// AfterControlStatements: true
+ /// AfterFunctionDefinitionName: true
+ /// \endcode
+ struct SpaceBeforeParensCustom {
+ /// If ``true``, put space between control statement keywords
+ /// (for/if/while...) and opening parentheses.
+ /// \code
+ /// true: false:
+ /// if (...) {} vs. if(...) {}
+ /// \endcode
+ bool AfterControlStatements;
+ /// If ``true``, put space between foreach macros and opening parentheses.
+ /// \code
+ /// true: false:
+ /// FOREACH (...) vs. FOREACH(...)
+ /// <loop-body> <loop-body>
+ /// \endcode
+ bool AfterForeachMacros;
+ /// If ``true``, put a space between function declaration name and opening
+ /// parentheses.
+ /// \code
+ /// true: false:
+ /// void f (); vs. void f();
+ /// \endcode
+ bool AfterFunctionDeclarationName;
+ /// If ``true``, put a space between function definition name and opening
+ /// parentheses.
+ /// \code
+ /// true: false:
+ /// void f () {} vs. void f() {}
+ /// \endcode
+ bool AfterFunctionDefinitionName;
+ /// If ``true``, put space between if macros and opening parentheses.
+ /// \code
+ /// true: false:
+ /// IF (...) vs. IF(...)
+ /// <conditional-body> <conditional-body>
+ /// \endcode
+ bool AfterIfMacros;
+ /// If ``true``, put a space between alternative operator ``not`` and the
+ /// opening parenthesis.
+ /// \code
+ /// true: false:
+ /// return not (a || b); vs. return not(a || b);
+ /// \endcode
+ bool AfterNot;
+ /// If ``true``, put a space between operator overloading and opening
+ /// parentheses.
+ /// \code
+ /// true: false:
+ /// void operator++ (int a); vs. void operator++(int a);
+ /// object.operator++ (10); object.operator++(10);
+ /// \endcode
+ bool AfterOverloadedOperator;
+ /// If ``true``, put a space between operator ``new``/``delete`` and opening
+ /// parenthesis.
+ /// \code
+ /// true: false:
+ /// new (buf) T; vs. new(buf) T;
+ /// delete (buf) T; delete(buf) T;
+ /// \endcode
+ bool AfterPlacementOperator;
+ /// If ``true``, put space between requires keyword in a requires clause and
+ /// opening parentheses, if there is one.
+ /// \code
+ /// true: false:
+ /// template<typename T> vs. template<typename T>
+ /// requires (A<T> && B<T>) requires(A<T> && B<T>)
+ /// ... ...
+ /// \endcode
+ bool AfterRequiresInClause;
+ /// If ``true``, put space between requires keyword in a requires expression
+ /// and opening parentheses.
+ /// \code
+ /// true: false:
+ /// template<typename T> vs. template<typename T>
+ /// concept C = requires (T t) { concept C = requires(T t) {
+ /// ... ...
+ /// } }
+ /// \endcode
+ bool AfterRequiresInExpression;
+ /// If ``true``, put a space before opening parentheses only if the
+ /// parentheses are not empty.
+ /// \code
+ /// true: false:
+ /// void f (int a); vs. void f();
+ /// f (a); f();
+ /// \endcode
+ bool BeforeNonEmptyParentheses;
+
+ SpaceBeforeParensCustom()
+ : AfterControlStatements(false), AfterForeachMacros(false),
+ AfterFunctionDeclarationName(false),
+ AfterFunctionDefinitionName(false), AfterIfMacros(false),
+ AfterNot(false), AfterOverloadedOperator(false),
+ AfterPlacementOperator(true), AfterRequiresInClause(false),
+ AfterRequiresInExpression(false), BeforeNonEmptyParentheses(false) {}
+
+ bool operator==(const SpaceBeforeParensCustom &Other) const {
+ return AfterControlStatements == Other.AfterControlStatements &&
+ AfterForeachMacros == Other.AfterForeachMacros &&
+ AfterFunctionDeclarationName ==
+ Other.AfterFunctionDeclarationName &&
+ AfterFunctionDefinitionName == Other.AfterFunctionDefinitionName &&
+ AfterIfMacros == Other.AfterIfMacros &&
+ AfterNot == Other.AfterNot &&
+ AfterOverloadedOperator == Other.AfterOverloadedOperator &&
+ AfterPlacementOperator == Other.AfterPlacementOperator &&
+ AfterRequiresInClause == Other.AfterRequiresInClause &&
+ AfterRequiresInExpression == Other.AfterRequiresInExpression &&
+ BeforeNonEmptyParentheses == Other.BeforeNonEmptyParentheses;
+ }
+ };
+
+ /// Control of individual space before parentheses.
+ ///
+ /// If ``SpaceBeforeParens`` is set to ``Custom``, use this to specify
+ /// how each individual space before parentheses case should be handled.
+ /// Otherwise, this is ignored.
+ /// \code{.yaml}
+ /// # Example of usage:
+ /// SpaceBeforeParens: Custom
+ /// SpaceBeforeParensOptions:
+ /// AfterControlStatements: true
+ /// AfterFunctionDefinitionName: true
+ /// \endcode
+ /// \version 14
+ SpaceBeforeParensCustom SpaceBeforeParensOptions;
+
+ /// If ``true``, spaces will be before ``[``.
+ /// Lambdas will not be affected. Only the first ``[`` will get a space added.
+ /// \code
+ /// true: false:
+ /// int a [5]; vs. int a[5];
+ /// int a [5][5]; vs. int a[5][5];
+ /// \endcode
+ /// \version 10
+ bool SpaceBeforeSquareBrackets;
+
+ /// If ``false``, spaces will be removed before range-based for loop
+ /// colon.
+ /// \code
+ /// true: false:
+ /// for (auto v : values) {} vs. for(auto v: values) {}
+ /// \endcode
+ /// \version 7
+ bool SpaceBeforeRangeBasedForLoopColon;
+
+ /// This option is **deprecated**. See ``Block`` of ``SpaceInEmptyBraces``.
+ /// \version 10
+ // bool SpaceInEmptyBlock;
+
+ /// Style of when to insert a space in empty braces.
+ enum SpaceInEmptyBracesStyle : int8_t {
+ /// Always insert a space in empty braces.
+ /// \code
+ /// void f() { }
+ /// class Unit { };
+ /// auto a = [] { };
+ /// int x{ };
+ /// \endcode
+ SIEB_Always,
+ /// Only insert a space in empty blocks.
+ /// \code
+ /// void f() { }
+ /// class Unit { };
+ /// auto a = [] { };
+ /// int x{};
+ /// \endcode
+ SIEB_Block,
+ /// Never insert a space in empty braces.
+ /// \code
+ /// void f() {}
+ /// class Unit {};
+ /// auto a = [] {};
+ /// int x{};
+ /// \endcode
+ SIEB_Never
+ };
+
+ /// Specifies when to insert a space in empty braces.
+ /// \note
+ /// This option doesn't apply to initializer braces if
+ /// ``Cpp11BracedListStyle`` is not ``Block``.
+ /// \endnote
+ /// \version 22
+ SpaceInEmptyBracesStyle SpaceInEmptyBraces;
+
+ /// If ``true``, spaces may be inserted into ``()``.
+ /// This option is **deprecated**. See ``InEmptyParentheses`` of
+ /// ``SpacesInParensOptions``.
+ /// \version 3.7
+ // bool SpaceInEmptyParentheses;
+
+ /// The number of spaces before trailing line comments
+ /// (``//`` - comments).
+ ///
+ /// This does not affect trailing block comments (``/*`` - comments) as those
+ /// commonly have different usage patterns and a number of special cases. In
+ /// the case of Verilog, it doesn't affect a comment right after the opening
+ /// parenthesis in the port or parameter list in a module header, because it
+ /// is probably for the port on the following line instead of the parenthesis
+ /// it follows.
+ /// \code
+ /// SpacesBeforeTrailingComments: 3
+ /// void f() {
+ /// if (true) { // foo1
+ /// f(); // bar
+ /// } // foo
+ /// }
+ /// \endcode
+ /// \version 3.7
+ unsigned SpacesBeforeTrailingComments;
+
+ /// Styles for adding spacing after ``<`` and before ``>``
+ /// in template argument lists.
+ enum SpacesInAnglesStyle : int8_t {
+ /// Remove spaces after ``<`` and before ``>``.
+ /// \code
+ /// static_cast<int>(arg);
+ /// std::function<void(int)> fct;
+ /// \endcode
+ SIAS_Never,
+ /// Add spaces after ``<`` and before ``>``.
+ /// \code
+ /// static_cast< int >(arg);
+ /// std::function< void(int) > fct;
+ /// \endcode
+ SIAS_Always,
+ /// Keep a single space after ``<`` and before ``>`` if any spaces were
+ /// present. Option ``Standard: Cpp03`` takes precedence.
+ SIAS_Leave
+ };
+ /// The SpacesInAnglesStyle to use for template argument lists.
+ /// \version 3.4
+ SpacesInAnglesStyle SpacesInAngles;
+
+ /// If ``true``, spaces will be inserted around if/for/switch/while
+ /// conditions.
+ /// This option is **deprecated**. See ``InConditionalStatements`` of
+ /// ``SpacesInParensOptions``.
+ /// \version 10
+ // bool SpacesInConditionalStatement;
+
+ /// If ``true``, spaces are inserted inside container literals (e.g. ObjC and
+ /// Javascript array and dict literals). For JSON, use
+ /// ``SpaceBeforeJsonColon`` instead.
+ /// \code{.js}
+ /// true: false:
+ /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
+ /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
+ /// \endcode
+ /// \version 3.7
+ bool SpacesInContainerLiterals;
+
+ /// If ``true``, spaces may be inserted into C style casts.
+ /// This option is **deprecated**. See ``InCStyleCasts`` of
+ /// ``SpacesInParensOptions``.
+ /// \version 3.7
+ // bool SpacesInCStyleCastParentheses;
+
+ /// Control of spaces within a single line comment.
+ struct SpacesInLineComment {
+ /// The minimum number of spaces at the start of the comment.
+ unsigned Minimum;
+ /// The maximum number of spaces at the start of the comment.
+ unsigned Maximum;
+ };
+
+ /// How many spaces are allowed at the start of a line comment. To disable the
+ /// maximum set it to ``-1``, apart from that the maximum takes precedence
+ /// over the minimum.
+ /// \code
+ /// Minimum = 1
+ /// Maximum = -1
+ /// // One space is forced
+ ///
+ /// // but more spaces are possible
+ ///
+ /// Minimum = 0
+ /// Maximum = 0
+ /// //Forces to start every comment directly after the slashes
+ /// \endcode
+ ///
+ /// Note that in line comment sections the relative indent of the subsequent
+ /// lines is kept, that means the following:
+ /// \code
+ /// before: after:
+ /// Minimum: 1
+ /// //if (b) { // if (b) {
+ /// // return true; // return true;
+ /// //} // }
+ ///
+ /// Maximum: 0
+ /// /// List: ///List:
+ /// /// - Foo /// - Foo
+ /// /// - Bar /// - Bar
+ /// \endcode
+ ///
+ /// This option has only effect if ``ReflowComments`` is set to ``true``.
+ /// \version 13
+ SpacesInLineComment SpacesInLineCommentPrefix;
+
+ /// Different ways to put a space before opening and closing parentheses.
+ enum SpacesInParensStyle : int8_t {
+ /// Never put a space in parentheses.
+ /// \code
+ /// void f() {
+ /// if(true) {
+ /// f();
+ /// }
+ /// }
+ /// \endcode
+ SIPO_Never,
+ /// Configure each individual space in parentheses in
+ /// `SpacesInParensOptions`.
+ SIPO_Custom,
+ };
+
+ /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
+ /// This option is **deprecated**. The previous behavior is preserved by using
+ /// ``SpacesInParens`` with ``Custom`` and by setting all
+ /// ``SpacesInParensOptions`` to ``true`` except for ``InCStyleCasts`` and
+ /// ``InEmptyParentheses``.
+ /// \version 3.7
+ // bool SpacesInParentheses;
+
+ /// Defines in which cases spaces will be inserted after ``(`` and before
+ /// ``)``.
+ /// \version 17
+ SpacesInParensStyle SpacesInParens;
+
+ /// Precise control over the spacing in parentheses.
+ /// \code
+ /// # Should be declared this way:
+ /// SpacesInParens: Custom
+ /// SpacesInParensOptions:
+ /// ExceptDoubleParentheses: false
+ /// InConditionalStatements: true
+ /// Other: true
+ /// \endcode
+ struct SpacesInParensCustom {
+ /// Override any of the following options to prevent addition of space
+ /// when both opening and closing parentheses use multiple parentheses.
+ /// \code
+ /// true:
+ /// __attribute__(( noreturn ))
+ /// __decltype__(( x ))
+ /// if (( a = b ))
+ /// \endcode
+ /// false:
+ /// Uses the applicable option.
+ bool ExceptDoubleParentheses;
+ /// Put a space in parentheses only inside conditional statements
+ /// (``for/if/while/switch...``).
+ /// \code
+ /// true: false:
+ /// if ( a ) { ... } vs. if (a) { ... }
+ /// while ( i < 5 ) { ... } while (i < 5) { ... }
+ /// \endcode
+ bool InConditionalStatements;
+ /// Put a space in C style casts.
+ /// \code
+ /// true: false:
+ /// x = ( int32 )y vs. x = (int32)y
+ /// y = (( int (*)(int) )foo)(x); y = ((int (*)(int))foo)(x);
+ /// \endcode
+ bool InCStyleCasts;
+ /// Insert a space in empty parentheses, i.e. ``()``.
+ /// \code
+ /// true: false:
+ /// void f( ) { vs. void f() {
+ /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
+ /// if (true) { if (true) {
+ /// f( ); f();
+ /// } }
+ /// } }
+ /// \endcode
+ bool InEmptyParentheses;
+ /// Put a space in parentheses not covered by preceding options.
+ /// \code
+ /// true: false:
+ /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
+ /// \endcode
+ bool Other;
+
+ SpacesInParensCustom()
+ : ExceptDoubleParentheses(false), InConditionalStatements(false),
+ InCStyleCasts(false), InEmptyParentheses(false), Other(false) {}
+
+ SpacesInParensCustom(bool ExceptDoubleParentheses,
+ bool InConditionalStatements, bool InCStyleCasts,
+ bool InEmptyParentheses, bool Other)
+ : ExceptDoubleParentheses(ExceptDoubleParentheses),
+ InConditionalStatements(InConditionalStatements),
+ InCStyleCasts(InCStyleCasts), InEmptyParentheses(InEmptyParentheses),
+ Other(Other) {}
+
+ bool operator==(const SpacesInParensCustom &R) const {
+ return ExceptDoubleParentheses == R.ExceptDoubleParentheses &&
+ InConditionalStatements == R.InConditionalStatements &&
+ InCStyleCasts == R.InCStyleCasts &&
+ InEmptyParentheses == R.InEmptyParentheses && Other == R.Other;
+ }
+ bool operator!=(const SpacesInParensCustom &R) const {
+ return !(*this == R);
+ }
+ };
+
+ /// Control of individual spaces in parentheses.
+ ///
+ /// If ``SpacesInParens`` is set to ``Custom``, use this to specify
+ /// how each individual space in parentheses case should be handled.
+ /// Otherwise, this is ignored.
+ /// \code{.yaml}
+ /// # Example of usage:
+ /// SpacesInParens: Custom
+ /// SpacesInParensOptions:
+ /// ExceptDoubleParentheses: false
+ /// InConditionalStatements: true
+ /// InEmptyParentheses: true
+ /// \endcode
+ /// \version 17
+ SpacesInParensCustom SpacesInParensOptions;
+
+ /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
+ /// Lambdas without arguments or unspecified size array declarations will not
+ /// be affected.
+ /// \code
+ /// true: false:
+ /// int a[ 5 ]; vs. int a[5];
+ /// std::unique_ptr<int[]> foo() {} // Won't be affected
+ /// \endcode
+ /// \version 3.7
+ bool SpacesInSquareBrackets;
+
+ /// Supported language standards for parsing and formatting C++ constructs.
+ /// \code
+ /// Latest: vector<set<int>>
+ /// c++03 vs. vector<set<int> >
+ /// \endcode
+ ///
+ /// The correct way to spell a specific language version is e.g. ``c++11``.
+ /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
+ enum LanguageStandard : int8_t {
+ /// Parse and format as C++03.
+ /// ``Cpp03`` is a deprecated alias for ``c++03``
+ LS_Cpp03, // c++03
+ /// Parse and format as C++11.
+ LS_Cpp11, // c++11
+ /// Parse and format as C++14.
+ LS_Cpp14, // c++14
+ /// Parse and format as C++17.
+ LS_Cpp17, // c++17
+ /// Parse and format as C++20.
+ LS_Cpp20, // c++20
+ /// Parse and format using the latest supported language version.
+ /// ``Cpp11`` is a deprecated alias for ``Latest``
+ LS_Latest,
+ /// Automatic detection based on the input.
+ LS_Auto,
+ };
+
+ /// Parse and format C++ constructs compatible with this standard.
+ /// \code
+ /// c++03: latest:
+ /// vector<set<int> > x; vs. vector<set<int>> x;
+ /// \endcode
+ /// \version 3.7
+ LanguageStandard Standard;
+
+ /// Macros which are ignored in front of a statement, as if they were an
+ /// attribute. So that they are not parsed as identifier, for example for Qts
+ /// emit.
+ /// \code
+ /// AlignConsecutiveDeclarations: true
+ /// StatementAttributeLikeMacros: []
+ /// unsigned char data = 'x';
+ /// emit signal(data); // This is parsed as variable declaration.
+ ///
+ /// AlignConsecutiveDeclarations: true
+ /// StatementAttributeLikeMacros: [emit]
+ /// unsigned char data = 'x';
+ /// emit signal(data); // Now it's fine again.
+ /// \endcode
+ /// \version 12
+ std::vector<std::string> StatementAttributeLikeMacros;
+
+ /// A vector of macros that should be interpreted as complete statements.
+ ///
+ /// Typical macros are expressions and require a semicolon to be added.
+ /// Sometimes this is not the case, and this allows to make clang-format aware
+ /// of such cases.
+ ///
+ /// For example: Q_UNUSED
+ /// \version 8
+ std::vector<std::string> StatementMacros;
+
+ /// Works only when TableGenBreakInsideDAGArg is not DontBreak.
+ /// The string list needs to consist of identifiers in TableGen.
+ /// If any identifier is specified, this limits the line breaks by
+ /// TableGenBreakInsideDAGArg option only on DAGArg values beginning with
+ /// the specified identifiers.
+ ///
+ /// For example the configuration,
+ /// \code{.yaml}
+ /// TableGenBreakInsideDAGArg: BreakAll
+ /// TableGenBreakingDAGArgOperators: [ins, outs]
+ /// \endcode
+ ///
+ /// makes the line break only occurs inside DAGArgs beginning with the
+ /// specified identifiers ``ins`` and ``outs``.
+ ///
+ /// \code
+ /// let DAGArgIns = (ins
+ /// i32:$src1,
+ /// i32:$src2
+ /// );
+ /// let DAGArgOtherID = (other i32:$other1, i32:$other2);
+ /// let DAGArgBang = (!cast<SomeType>("Some") i32:$src1, i32:$src2)
+ /// \endcode
+ /// \version 19
+ std::vector<std::string> TableGenBreakingDAGArgOperators;
+
+ /// Different ways to control the format inside TableGen DAGArg.
+ enum DAGArgStyle : int8_t {
+ /// Never break inside DAGArg.
+ /// \code
+ /// let DAGArgIns = (ins i32:$src1, i32:$src2);
+ /// \endcode
+ DAS_DontBreak,
+ /// Break inside DAGArg after each list element but for the last.
+ /// This aligns to the first element.
+ /// \code
+ /// let DAGArgIns = (ins i32:$src1,
+ /// i32:$src2);
+ /// \endcode
+ DAS_BreakElements,
+ /// Break inside DAGArg after the operator and the all elements.
+ /// \code
+ /// let DAGArgIns = (ins
+ /// i32:$src1,
+ /// i32:$src2
+ /// );
+ /// \endcode
+ DAS_BreakAll,
+ };
+
+ /// The styles of the line break inside the DAGArg in TableGen.
+ /// \version 19
+ DAGArgStyle TableGenBreakInsideDAGArg;
+
+ /// The number of columns used for tab stops.
+ /// \version 3.7
+ unsigned TabWidth;
+
+ /// A vector of non-keyword identifiers that should be interpreted as template
+ /// names.
+ ///
+ /// A ``<`` after a template name is annotated as a template opener instead of
+ /// a binary operator.
+ ///
+ /// \version 20
+ std::vector<std::string> TemplateNames;
+
+ /// A vector of non-keyword identifiers that should be interpreted as type
+ /// names.
+ ///
+ /// A ``*``, ``&``, or ``&&`` between a type name and another non-keyword
+ /// identifier is annotated as a pointer or reference token instead of a
+ /// binary operator.
+ ///
+ /// \version 17
+ std::vector<std::string> TypeNames;
+
+ /// A vector of macros that should be interpreted as type declarations instead
+ /// of as function calls.
+ ///
+ /// These are expected to be macros of the form:
+ /// \code
+ /// STACK_OF(...)
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// TypenameMacros: [STACK_OF, LIST]
+ /// \endcode
+ ///
+ /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
+ /// \version 9
+ std::vector<std::string> TypenameMacros;
+
+ /// This option is **deprecated**. See ``LF`` and ``CRLF`` of ``LineEnding``.
+ /// \version 10
+ // bool UseCRLF;
+
+ /// Different ways to use tab in formatting.
+ enum UseTabStyle : int8_t {
+ /// Never use tab.
+ UT_Never,
+ /// Use tabs only for indentation.
+ UT_ForIndentation,
+ /// Fill all leading whitespace with tabs, and use spaces for alignment that
+ /// appears within a line (e.g. consecutive assignments and declarations).
+ UT_ForContinuationAndIndentation,
+ /// Use tabs for line continuation and indentation, and spaces for
+ /// alignment.
+ UT_AlignWithSpaces,
+ /// Use tabs whenever we need to fill whitespace that spans at least from
+ /// one tab stop to the next one.
+ UT_Always
+ };
+
+ /// The way to use tab characters in the resulting file.
+ /// \version 3.7
+ UseTabStyle UseTab;
+
+ /// A vector of non-keyword identifiers that should be interpreted as variable
+ /// template names.
+ ///
+ /// A ``)`` after a variable template instantiation is **not** annotated as
+ /// the closing parenthesis of C-style cast operator.
+ ///
+ /// \version 20
+ std::vector<std::string> VariableTemplates;
+
+ /// For Verilog, put each port on its own line in module instantiations.
+ /// \code
+ /// true:
+ /// ffnand ff1(.q(),
+ /// .qbar(out1),
+ /// .clear(in1),
+ /// .preset(in2));
+ ///
+ /// false:
+ /// ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));
+ /// \endcode
+ /// \version 17
+ bool VerilogBreakBetweenInstancePorts;
+
+ /// A vector of macros which are whitespace-sensitive and should not
+ /// be touched.
+ ///
+ /// These are expected to be macros of the form:
+ /// \code
+ /// STRINGIZE(...)
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// WhitespaceSensitiveMacros: [STRINGIZE, PP_STRINGIZE]
+ /// \endcode
+ ///
+ /// For example: BOOST_PP_STRINGIZE
+ /// \version 11
+ std::vector<std::string> WhitespaceSensitiveMacros;
+
+ /// Different styles for wrapping namespace body with empty lines.
+ enum WrapNamespaceBodyWithEmptyLinesStyle : int8_t {
+ /// Remove all empty lines at the beginning and the end of namespace body.
+ /// \code
+ /// namespace N1 {
+ /// namespace N2 {
+ /// function();
+ /// }
+ /// }
+ /// \endcode
+ WNBWELS_Never,
+ /// Always have at least one empty line at the beginning and the end of
+ /// namespace body except that the number of empty lines between consecutive
+ /// nested namespace definitions is not increased.
+ /// \code
+ /// namespace N1 {
+ /// namespace N2 {
+ ///
+ /// function();
+ ///
+ /// }
+ /// }
+ /// \endcode
+ WNBWELS_Always,
+ /// Keep existing newlines at the beginning and the end of namespace body.
+ /// ``MaxEmptyLinesToKeep`` still applies.
+ WNBWELS_Leave
+ };
+
+ /// Wrap namespace body with empty lines.
+ /// \version 20
+ WrapNamespaceBodyWithEmptyLinesStyle WrapNamespaceBodyWithEmptyLines;
+
+ bool operator==(const FormatStyle &R) const {
+ return AccessModifierOffset == R.AccessModifierOffset &&
+ AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
+ AlignArrayOfStructures == R.AlignArrayOfStructures &&
+ AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
+ AlignConsecutiveBitFields == R.AlignConsecutiveBitFields &&
+ AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
+ AlignConsecutiveMacros == R.AlignConsecutiveMacros &&
+ AlignConsecutiveShortCaseStatements ==
+ R.AlignConsecutiveShortCaseStatements &&
+ AlignConsecutiveTableGenBreakingDAGArgColons ==
+ R.AlignConsecutiveTableGenBreakingDAGArgColons &&
+ AlignConsecutiveTableGenCondOperatorColons ==
+ R.AlignConsecutiveTableGenCondOperatorColons &&
+ AlignConsecutiveTableGenDefinitionColons ==
+ R.AlignConsecutiveTableGenDefinitionColons &&
+ AlignEscapedNewlines == R.AlignEscapedNewlines &&
+ AlignOperands == R.AlignOperands &&
+ AlignTrailingComments == R.AlignTrailingComments &&
+ AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
+ AllowAllParametersOfDeclarationOnNextLine ==
+ R.AllowAllParametersOfDeclarationOnNextLine &&
+ AllowBreakBeforeNoexceptSpecifier ==
+ R.AllowBreakBeforeNoexceptSpecifier &&
+ AllowBreakBeforeQtProperty == R.AllowBreakBeforeQtProperty &&
+ AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
+ AllowShortCaseExpressionOnASingleLine ==
+ R.AllowShortCaseExpressionOnASingleLine &&
+ AllowShortCaseLabelsOnASingleLine ==
+ R.AllowShortCaseLabelsOnASingleLine &&
+ AllowShortCompoundRequirementOnASingleLine ==
+ R.AllowShortCompoundRequirementOnASingleLine &&
+ AllowShortEnumsOnASingleLine == R.AllowShortEnumsOnASingleLine &&
+ AllowShortFunctionsOnASingleLine ==
+ R.AllowShortFunctionsOnASingleLine &&
+ AllowShortIfStatementsOnASingleLine ==
+ R.AllowShortIfStatementsOnASingleLine &&
+ AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
+ AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
+ AllowShortNamespacesOnASingleLine ==
+ R.AllowShortNamespacesOnASingleLine &&
+ AllowShortRecordOnASingleLine == R.AllowShortRecordOnASingleLine &&
+ AlwaysBreakBeforeMultilineStrings ==
+ R.AlwaysBreakBeforeMultilineStrings &&
+ AttributeMacros == R.AttributeMacros &&
+ BinPackArguments == R.BinPackArguments &&
+ BinPackLongBracedList == R.BinPackLongBracedList &&
+ BinPackParameters == R.BinPackParameters &&
+ BitFieldColonSpacing == R.BitFieldColonSpacing &&
+ BracedInitializerIndentWidth == R.BracedInitializerIndentWidth &&
+ BreakAdjacentStringLiterals == R.BreakAdjacentStringLiterals &&
+ BreakAfterAttributes == R.BreakAfterAttributes &&
+ BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
+ BreakAfterOpenBracketBracedList ==
+ R.BreakAfterOpenBracketBracedList &&
+ BreakAfterOpenBracketFunction == R.BreakAfterOpenBracketFunction &&
+ BreakAfterOpenBracketIf == R.BreakAfterOpenBracketIf &&
+ BreakAfterOpenBracketLoop == R.BreakAfterOpenBracketLoop &&
+ BreakAfterOpenBracketSwitch == R.BreakAfterOpenBracketSwitch &&
+ BreakAfterReturnType == R.BreakAfterReturnType &&
+ BreakArrays == R.BreakArrays &&
+ BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
+ BreakBeforeBraces == R.BreakBeforeBraces &&
+ BreakBeforeCloseBracketBracedList ==
+ R.BreakBeforeCloseBracketBracedList &&
+ BreakBeforeCloseBracketFunction ==
+ R.BreakBeforeCloseBracketFunction &&
+ BreakBeforeCloseBracketIf == R.BreakBeforeCloseBracketIf &&
+ BreakBeforeCloseBracketLoop == R.BreakBeforeCloseBracketLoop &&
+ BreakBeforeCloseBracketSwitch == R.BreakBeforeCloseBracketSwitch &&
+ BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations &&
+ BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
+ BreakBeforeTemplateCloser == R.BreakBeforeTemplateCloser &&
+ BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
+ BreakBinaryOperations == R.BreakBinaryOperations &&
+ BreakConstructorInitializers == R.BreakConstructorInitializers &&
+ BreakFunctionDefinitionParameters ==
+ R.BreakFunctionDefinitionParameters &&
+ BreakInheritanceList == R.BreakInheritanceList &&
+ BreakStringLiterals == R.BreakStringLiterals &&
+ BreakTemplateDeclarations == R.BreakTemplateDeclarations &&
+ ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
+ CompactNamespaces == R.CompactNamespaces &&
+ ConstructorInitializerIndentWidth ==
+ R.ConstructorInitializerIndentWidth &&
+ ContinuationIndentWidth == R.ContinuationIndentWidth &&
+ Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
+ DerivePointerAlignment == R.DerivePointerAlignment &&
+ DisableFormat == R.DisableFormat &&
+ EmptyLineAfterAccessModifier == R.EmptyLineAfterAccessModifier &&
+ EmptyLineBeforeAccessModifier == R.EmptyLineBeforeAccessModifier &&
+ EnumTrailingComma == R.EnumTrailingComma &&
+ ExperimentalAutoDetectBinPacking ==
+ R.ExperimentalAutoDetectBinPacking &&
+ FixNamespaceComments == R.FixNamespaceComments &&
+ ForEachMacros == R.ForEachMacros &&
+ IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
+ IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
+ IncludeStyle.IncludeIsMainRegex ==
+ R.IncludeStyle.IncludeIsMainRegex &&
+ IncludeStyle.IncludeIsMainSourceRegex ==
+ R.IncludeStyle.IncludeIsMainSourceRegex &&
+ IncludeStyle.MainIncludeChar == R.IncludeStyle.MainIncludeChar &&
+ IndentAccessModifiers == R.IndentAccessModifiers &&
+ IndentCaseBlocks == R.IndentCaseBlocks &&
+ IndentCaseLabels == R.IndentCaseLabels &&
+ IndentExportBlock == R.IndentExportBlock &&
+ IndentExternBlock == R.IndentExternBlock &&
+ IndentGotoLabels == R.IndentGotoLabels &&
+ IndentPPDirectives == R.IndentPPDirectives &&
+ IndentRequiresClause == R.IndentRequiresClause &&
+ IndentWidth == R.IndentWidth &&
+ IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
+ InsertBraces == R.InsertBraces &&
+ InsertNewlineAtEOF == R.InsertNewlineAtEOF &&
+ IntegerLiteralSeparator == R.IntegerLiteralSeparator &&
+ JavaImportGroups == R.JavaImportGroups &&
+ JavaScriptQuotes == R.JavaScriptQuotes &&
+ JavaScriptWrapImports == R.JavaScriptWrapImports &&
+ KeepEmptyLines == R.KeepEmptyLines &&
+ KeepFormFeed == R.KeepFormFeed && Language == R.Language &&
+ LambdaBodyIndentation == R.LambdaBodyIndentation &&
+ LineEnding == R.LineEnding && MacroBlockBegin == R.MacroBlockBegin &&
+ MacroBlockEnd == R.MacroBlockEnd && Macros == R.Macros &&
+ MacrosSkippedByRemoveParentheses ==
+ R.MacrosSkippedByRemoveParentheses &&
+ MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
+ NamespaceIndentation == R.NamespaceIndentation &&
+ NamespaceMacros == R.NamespaceMacros &&
+ NumericLiteralCase == R.NumericLiteralCase &&
+ ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
+ ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
+ ObjCBreakBeforeNestedBlockParam ==
+ R.ObjCBreakBeforeNestedBlockParam &&
+ ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder &&
+ ObjCSpaceAfterMethodDeclarationPrefix ==
+ R.ObjCSpaceAfterMethodDeclarationPrefix &&
+ ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
+ ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
+ OneLineFormatOffRegex == R.OneLineFormatOffRegex &&
+ PackConstructorInitializers == R.PackConstructorInitializers &&
+ PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
+ PenaltyBreakBeforeFirstCallParameter ==
+ R.PenaltyBreakBeforeFirstCallParameter &&
+ PenaltyBreakBeforeMemberAccess == R.PenaltyBreakBeforeMemberAccess &&
+ PenaltyBreakComment == R.PenaltyBreakComment &&
+ PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
+ PenaltyBreakOpenParenthesis == R.PenaltyBreakOpenParenthesis &&
+ PenaltyBreakScopeResolution == R.PenaltyBreakScopeResolution &&
+ PenaltyBreakString == R.PenaltyBreakString &&
+ PenaltyBreakTemplateDeclaration ==
+ R.PenaltyBreakTemplateDeclaration &&
+ PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
+ PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
+ PointerAlignment == R.PointerAlignment &&
+ QualifierAlignment == R.QualifierAlignment &&
+ QualifierOrder == R.QualifierOrder &&
+ RawStringFormats == R.RawStringFormats &&
+ ReferenceAlignment == R.ReferenceAlignment &&
+ RemoveBracesLLVM == R.RemoveBracesLLVM &&
+ RemoveEmptyLinesInUnwrappedLines ==
+ R.RemoveEmptyLinesInUnwrappedLines &&
+ RemoveParentheses == R.RemoveParentheses &&
+ RemoveSemicolon == R.RemoveSemicolon &&
+ RequiresClausePosition == R.RequiresClausePosition &&
+ RequiresExpressionIndentation == R.RequiresExpressionIndentation &&
+ SeparateDefinitionBlocks == R.SeparateDefinitionBlocks &&
+ ShortNamespaceLines == R.ShortNamespaceLines &&
+ SkipMacroDefinitionBody == R.SkipMacroDefinitionBody &&
+ SortIncludes == R.SortIncludes &&
+ SortJavaStaticImport == R.SortJavaStaticImport &&
+ SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
+ SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
+ SpaceAfterOperatorKeyword == R.SpaceAfterOperatorKeyword &&
+ SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
+ SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
+ SpaceBeforeCaseColon == R.SpaceBeforeCaseColon &&
+ SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
+ SpaceBeforeCtorInitializerColon ==
+ R.SpaceBeforeCtorInitializerColon &&
+ SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
+ SpaceBeforeJsonColon == R.SpaceBeforeJsonColon &&
+ SpaceBeforeParens == R.SpaceBeforeParens &&
+ SpaceBeforeParensOptions == R.SpaceBeforeParensOptions &&
+ SpaceAroundPointerQualifiers == R.SpaceAroundPointerQualifiers &&
+ SpaceBeforeRangeBasedForLoopColon ==
+ R.SpaceBeforeRangeBasedForLoopColon &&
+ SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
+ SpaceInEmptyBraces == R.SpaceInEmptyBraces &&
+ SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
+ SpacesInAngles == R.SpacesInAngles &&
+ SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
+ SpacesInLineCommentPrefix.Minimum ==
+ R.SpacesInLineCommentPrefix.Minimum &&
+ SpacesInLineCommentPrefix.Maximum ==
+ R.SpacesInLineCommentPrefix.Maximum &&
+ SpacesInParens == R.SpacesInParens &&
+ SpacesInParensOptions == R.SpacesInParensOptions &&
+ SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
+ Standard == R.Standard &&
+ StatementAttributeLikeMacros == R.StatementAttributeLikeMacros &&
+ StatementMacros == R.StatementMacros &&
+ TableGenBreakingDAGArgOperators ==
+ R.TableGenBreakingDAGArgOperators &&
+ TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
+ TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
+ TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
+ UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
+ VerilogBreakBetweenInstancePorts ==
+ R.VerilogBreakBetweenInstancePorts &&
+ WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros &&
+ WrapNamespaceBodyWithEmptyLines == R.WrapNamespaceBodyWithEmptyLines;
+ }
+
+ std::optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
+
+ // Stores per-language styles. A FormatStyle instance inside has an empty
+ // StyleSet. A FormatStyle instance returned by the Get method has its
+ // StyleSet set to a copy of the originating StyleSet, effectively keeping the
+ // internal representation of that StyleSet alive.
+ //
+ // The memory management and ownership reminds of a birds nest: chicks
+ // leaving the nest take photos of the nest with them.
+ struct FormatStyleSet {
+ typedef std::map<LanguageKind, FormatStyle> MapType;
+
+ std::optional<FormatStyle> Get(LanguageKind Language) const;
+
+ // Adds \p Style to this FormatStyleSet. Style must not have an associated
+ // FormatStyleSet.
+ // Style.Language should be different than LK_None. If this FormatStyleSet
+ // already contains an entry for Style.Language, that gets replaced with the
+ // passed Style.
+ void Add(FormatStyle Style);
+
+ // Clears this FormatStyleSet.
+ void Clear();
+
+ private:
+ std::shared_ptr<MapType> Styles;
+ };
+
+ static FormatStyleSet BuildStyleSetFromConfiguration(
+ const FormatStyle &MainStyle,
+ const std::vector<FormatStyle> &ConfigurationStyles);
+
+private:
+ FormatStyleSet StyleSet;
+
+ friend std::error_code
+ parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style,
+ bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler,
+ void *DiagHandlerCtxt, bool IsDotHFile);
+};
+
+/// Returns a format style complying with the LLVM coding standards:
+/// http://llvm.org/docs/CodingStandards.html.
+FormatStyle
+getLLVMStyle(FormatStyle::LanguageKind Language = FormatStyle::LK_Cpp);
+
+/// Returns a format style complying with one of Google's style guides:
+/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
+/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
+/// https://developers.google.com/protocol-buffers/docs/style.
+FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
+
+/// Returns a format style complying with Chromium's style guide:
+/// http://www.chromium.org/developers/coding-style.
+FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
+
+/// Returns a format style complying with Mozilla's style guide:
+/// https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html.
+FormatStyle getMozillaStyle();
+
+/// Returns a format style complying with Webkit's style guide:
+/// http://www.webkit.org/coding/coding-style.html
+FormatStyle getWebKitStyle();
+
+/// Returns a format style complying with GNU Coding Standards:
+/// http://www.gnu.org/prep/standards/standards.html
+FormatStyle getGNUStyle();
+
+/// Returns a format style complying with Microsoft style guide:
+/// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
+FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language);
+
+FormatStyle getClangFormatStyle();
+
+/// Returns style indicating formatting should be not applied at all.
+FormatStyle getNoStyle();
+
+/// Gets a predefined style for the specified language by name.
+///
+/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
+/// compared case-insensitively.
+///
+/// Returns ``true`` if the Style has been set.
+bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
+ FormatStyle *Style);
+
+/// Parse configuration from YAML-formatted text.
+///
+/// Style->Language is used to get the base style, if the ``BasedOnStyle``
+/// option is present.
+///
+/// The FormatStyleSet of Style is reset.
+///
+/// When ``BasedOnStyle`` is not present, options not present in the YAML
+/// document, are retained in \p Style.
+///
+/// If AllowUnknownOptions is true, no errors are emitted if unknown
+/// format options are occurred.
+///
+/// If set all diagnostics are emitted through the DiagHandler.
+std::error_code
+parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
+ void *DiagHandlerCtx = nullptr, bool IsDotHFile = false);
+
+/// Like above but accepts an unnamed buffer.
+inline std::error_code parseConfiguration(StringRef Config, FormatStyle *Style,
+ bool AllowUnknownOptions = false,
+ bool IsDotHFile = false) {
+ return parseConfiguration(llvm::MemoryBufferRef(Config, "YAML"), Style,
+ AllowUnknownOptions, /*DiagHandler=*/nullptr,
+ /*DiagHandlerCtx=*/nullptr, IsDotHFile);
+}
+
+/// Gets configuration in a YAML string.
+std::string configurationAsText(const FormatStyle &Style);
+
+/// Returns the replacements necessary to sort all ``#include`` blocks
+/// that are affected by ``Ranges``.
+tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName,
+ unsigned *Cursor = nullptr);
+
+/// Returns the replacements corresponding to applying and formatting
+/// \p Replaces on success; otheriwse, return an llvm::Error carrying
+/// llvm::StringError.
+Expected<tooling::Replacements>
+formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
+ const FormatStyle &Style);
+
+/// Returns the replacements corresponding to applying \p Replaces and
+/// cleaning up the code after that on success; otherwise, return an llvm::Error
+/// carrying llvm::StringError.
+/// This also supports inserting/deleting C++ #include directives:
+/// * If a replacement has offset UINT_MAX, length 0, and a replacement text
+/// that is an #include directive, this will insert the #include into the
+/// correct block in the \p Code.
+/// * If a replacement has offset UINT_MAX, length 1, and a replacement text
+/// that is the name of the header to be removed, the header will be removed
+/// from \p Code if it exists.
+/// The include manipulation is done via ``tooling::HeaderInclude``, see its
+/// documentation for more details on how include insertion points are found and
+/// what edits are produced.
+Expected<tooling::Replacements>
+cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
+ const FormatStyle &Style);
+
+/// Represents the status of a formatting attempt.
+struct FormattingAttemptStatus {
+ /// A value of ``false`` means that any of the affected ranges were not
+ /// formatted due to a non-recoverable syntax error.
+ bool FormatComplete = true;
+
+ /// If ``FormatComplete`` is false, ``Line`` records a one-based
+ /// original line number at which a syntax error might have occurred. This is
+ /// based on a best-effort analysis and could be imprecise.
+ unsigned Line = 0;
+};
+
+/// Reformats the given \p Ranges in \p Code.
+///
+/// Each range is extended on either end to its next bigger logic unit, i.e.
+/// everything that might influence its formatting or might be influenced by its
+/// formatting.
+///
+/// Returns the ``Replacements`` necessary to make all \p Ranges comply with
+/// \p Style.
+///
+/// If ``Status`` is non-null, its value will be populated with the status of
+/// this formatting attempt. See \c FormattingAttemptStatus.
+tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName = "<stdin>",
+ FormattingAttemptStatus *Status = nullptr);
+
+/// Same as above, except if ``IncompleteFormat`` is non-null, its value
+/// will be set to true if any of the affected ranges were not formatted due to
+/// a non-recoverable syntax error.
+tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName, bool *IncompleteFormat);
+
+/// Clean up any erroneous/redundant code in the given \p Ranges in \p
+/// Code.
+///
+/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
+tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName = "<stdin>");
+
+/// Fix namespace end comments in the given \p Ranges in \p Code.
+///
+/// Returns the ``Replacements`` that fix the namespace comments in all
+/// \p Ranges in \p Code.
+tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
+ StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName = "<stdin>");
+
+/// Inserts or removes empty lines separating definition blocks including
+/// classes, structs, functions, namespaces, and enums in the given \p Ranges in
+/// \p Code.
+///
+/// Returns the ``Replacements`` that inserts or removes empty lines separating
+/// definition blocks in all \p Ranges in \p Code.
+tooling::Replacements separateDefinitionBlocks(const FormatStyle &Style,
+ StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName = "<stdin>");
+
+/// Sort consecutive using declarations in the given \p Ranges in
+/// \p Code.
+///
+/// Returns the ``Replacements`` that sort the using declarations in all
+/// \p Ranges in \p Code.
+tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
+ StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName = "<stdin>");
+
+/// Returns the ``LangOpts`` that the formatter expects you to set.
+///
+/// \param Style determines specific settings for lexing mode.
+LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
+
+/// Description to be used for help text for a ``llvm::cl`` option for
+/// specifying format style. The description is closely related to the operation
+/// of ``getStyle()``.
+extern const char *StyleOptionHelpDescription;
+
+/// The suggested format style to use by default. This allows tools using
+/// ``getStyle`` to have a consistent default style.
+/// Different builds can modify the value to the preferred styles.
+extern const char *DefaultFormatStyle;
+
+/// The suggested predefined style to use as the fallback style in ``getStyle``.
+/// Different builds can modify the value to the preferred styles.
+extern const char *DefaultFallbackStyle;
+
+/// Construct a FormatStyle based on ``StyleName``.
+///
+/// ``StyleName`` can take several forms:
+/// * "{<key>: <value>, ...}" - Set specic style parameters.
+/// * "<style name>" - One of the style names supported by getPredefinedStyle().
+/// * "file" - Load style configuration from a file called ``.clang-format``
+/// located in one of the parent directories of ``FileName`` or the current
+/// directory if ``FileName`` is empty.
+/// * "file:<format_file_path>" to explicitly specify the configuration file to
+/// use.
+///
+/// \param[in] StyleName Style name to interpret according to the description
+/// above.
+/// \param[in] FileName Path to start search for .clang-format if ``StyleName``
+/// == "file".
+/// \param[in] FallbackStyle The name of a predefined style used to fallback to
+/// in case \p StyleName is "file" and no file can be found.
+/// \param[in] Code The actual code to be formatted. Used to determine the
+/// language if the filename isn't sufficient.
+/// \param[in] FS The underlying file system, in which the file resides. By
+/// default, the file system is the real file system.
+/// \param[in] AllowUnknownOptions If true, unknown format options only
+/// emit a warning. If false, errors are emitted on unknown format
+/// options.
+///
+/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
+/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
+/// determined, returns an Error.
+Expected<FormatStyle>
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
+
+// Guesses the language from the ``FileName`` and ``Code`` to be formatted.
+// Defaults to FormatStyle::LK_Cpp.
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
+
+// Returns a string representation of ``Language``.
+inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
+ switch (Language) {
+ case FormatStyle::LK_C:
+ return "C";
+ case FormatStyle::LK_Cpp:
+ return "C++";
+ case FormatStyle::LK_CSharp:
+ return "CSharp";
+ case FormatStyle::LK_ObjC:
+ return "Objective-C";
+ case FormatStyle::LK_Java:
+ return "Java";
+ case FormatStyle::LK_JavaScript:
+ return "JavaScript";
+ case FormatStyle::LK_Json:
+ return "Json";
+ case FormatStyle::LK_Proto:
+ return "Proto";
+ case FormatStyle::LK_TableGen:
+ return "TableGen";
+ case FormatStyle::LK_TextProto:
+ return "TextProto";
+ case FormatStyle::LK_Verilog:
+ return "Verilog";
+ default:
+ return "Unknown";
+ }
+}
+
+bool isClangFormatOn(StringRef Comment);
+bool isClangFormatOff(StringRef Comment);
+
+} // end namespace format
+} // end namespace clang
+
+template <>
+struct std::is_error_code_enum<clang::format::ParseError> : std::true_type {};
+
+#endif // LLVM_CLANG_FORMAT_FORMAT_H
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 93859d7ea9c4a..8fdca3fcedd54 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1,4769 +1,4772 @@
-//===--- Format.cpp - Format C++ code -------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-///
-/// \file
-/// This file implements functions declared in Format.h. This will be
-/// split into separate files as we go.
-///
-//===----------------------------------------------------------------------===//
-
-#include "clang/Format/Format.h"
-#include "DefinitionBlockSeparator.h"
-#include "IntegerLiteralSeparatorFixer.h"
-#include "NamespaceEndCommentsFixer.h"
-#include "NumericLiteralCaseFixer.h"
-#include "ObjCPropertyAttributeOrderFixer.h"
-#include "QualifierAlignmentFixer.h"
-#include "SortJavaScriptImports.h"
-#include "UnwrappedLineFormatter.h"
-#include "UsingDeclarationsSorter.h"
-#include "clang/Tooling/Inclusions/HeaderIncludes.h"
-#include "llvm/ADT/Sequence.h"
-#include "llvm/ADT/StringSet.h"
-#include <limits>
-
-#define DEBUG_TYPE "format-formatter"
-
-using clang::format::FormatStyle;
-
-LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
-LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::BinaryOperationBreakRule)
-LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tok::TokenKind)
-
-enum BracketAlignmentStyle : int8_t {
- BAS_Align,
- BAS_DontAlign,
- BAS_AlwaysBreak,
- BAS_BlockIndent
-};
-
-namespace llvm {
-namespace yaml {
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
- static void
- enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::BBNSS_Never);
- IO.enumCase(Value, "OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
- IO.enumCase(Value, "Always", FormatStyle::BBNSS_Always);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
- static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::AlignConsecutiveStyle{});
- IO.enumCase(Value, "Consecutive",
- FormatStyle::AlignConsecutiveStyle(
- {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
- /*AcrossComments=*/false, /*AlignCompound=*/false,
- /*AlignFunctionDeclarations=*/true,
- /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
- IO.enumCase(Value, "AcrossEmptyLines",
- FormatStyle::AlignConsecutiveStyle(
- {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
- /*AcrossComments=*/false, /*AlignCompound=*/false,
- /*AlignFunctionDeclarations=*/true,
- /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
- IO.enumCase(Value, "AcrossComments",
- FormatStyle::AlignConsecutiveStyle(
- {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
- /*AcrossComments=*/true, /*AlignCompound=*/false,
- /*AlignFunctionDeclarations=*/true,
- /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
- IO.enumCase(Value, "AcrossEmptyLinesAndComments",
- FormatStyle::AlignConsecutiveStyle(
- {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
- /*AcrossComments=*/true, /*AlignCompound=*/false,
- /*AlignFunctionDeclarations=*/true,
- /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
-
- // For backward compatibility.
- IO.enumCase(Value, "true",
- FormatStyle::AlignConsecutiveStyle(
- {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
- /*AcrossComments=*/false, /*AlignCompound=*/false,
- /*AlignFunctionDeclarations=*/true,
- /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
- IO.enumCase(Value, "false", FormatStyle::AlignConsecutiveStyle{});
- }
-
- static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
- IO.mapOptional("Enabled", Value.Enabled);
- IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
- IO.mapOptional("AcrossComments", Value.AcrossComments);
- IO.mapOptional("AlignCompound", Value.AlignCompound);
- IO.mapOptional("AlignFunctionDeclarations",
- Value.AlignFunctionDeclarations);
- IO.mapOptional("AlignFunctionPointers", Value.AlignFunctionPointers);
- IO.mapOptional("PadOperators", Value.PadOperators);
- }
-};
-
-template <>
-struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
- static void mapping(IO &IO,
- FormatStyle::ShortCaseStatementsAlignmentStyle &Value) {
- IO.mapOptional("Enabled", Value.Enabled);
- IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
- IO.mapOptional("AcrossComments", Value.AcrossComments);
- IO.mapOptional("AlignCaseArrows", Value.AlignCaseArrows);
- IO.mapOptional("AlignCaseColons", Value.AlignCaseColons);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
- static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value) {
- IO.enumCase(Value, "Always", FormatStyle::ABS_Always);
- IO.enumCase(Value, "Leave", FormatStyle::ABS_Leave);
- IO.enumCase(Value, "LeaveAll", FormatStyle::ABS_LeaveAll);
- IO.enumCase(Value, "Never", FormatStyle::ABS_Never);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
- static void enumeration(IO &IO,
- FormatStyle::ArrayInitializerAlignmentStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::AIAS_None);
- IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
- IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
- static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
- IO.enumCase(Value, "All", FormatStyle::BOS_All);
- IO.enumCase(Value, "true", FormatStyle::BOS_All);
- IO.enumCase(Value, "None", FormatStyle::BOS_None);
- IO.enumCase(Value, "false", FormatStyle::BOS_None);
- IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
- static void enumeration(IO &IO, FormatStyle::BinPackParametersStyle &Value) {
- IO.enumCase(Value, "BinPack", FormatStyle::BPPS_BinPack);
- IO.enumCase(Value, "OnePerLine", FormatStyle::BPPS_OnePerLine);
- IO.enumCase(Value, "AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::BPPS_BinPack);
- IO.enumCase(Value, "false", FormatStyle::BPPS_OnePerLine);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
- static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
- IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
- IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
- IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
- static void enumeration(IO &IO,
- FormatStyle::BitFieldColonSpacingStyle &Value) {
- IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
- IO.enumCase(Value, "None", FormatStyle::BFCS_None);
- IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
- IO.enumCase(Value, "After", FormatStyle::BFCS_After);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
- static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
- IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
- IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
- IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
- IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
- IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
- IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
- IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
- IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
- IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
- static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
- IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
- IO.mapOptional("AfterClass", Wrapping.AfterClass);
- IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
- IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
- IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
- IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
- IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
- IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
- IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
- IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
- IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
- IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
- IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
- IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
- IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
- IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
- IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
- IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
- }
-};
-
-template <> struct ScalarEnumerationTraits<BracketAlignmentStyle> {
- static void enumeration(IO &IO, BracketAlignmentStyle &Value) {
- IO.enumCase(Value, "Align", BAS_Align);
- IO.enumCase(Value, "DontAlign", BAS_DontAlign);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", BAS_Align);
- IO.enumCase(Value, "false", BAS_DontAlign);
- IO.enumCase(Value, "AlwaysBreak", BAS_AlwaysBreak);
- IO.enumCase(Value, "BlockIndent", BAS_BlockIndent);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<
- FormatStyle::BraceWrappingAfterControlStatementStyle> {
- static void
- enumeration(IO &IO,
- FormatStyle::BraceWrappingAfterControlStatementStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
- IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
- IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
- IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<
- FormatStyle::BreakBeforeConceptDeclarationsStyle> {
- static void
- enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::BBCDS_Never);
- IO.enumCase(Value, "Allowed", FormatStyle::BBCDS_Allowed);
- IO.enumCase(Value, "Always", FormatStyle::BBCDS_Always);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::BBCDS_Always);
- IO.enumCase(Value, "false", FormatStyle::BBCDS_Allowed);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
- static void enumeration(IO &IO,
- FormatStyle::BreakBeforeInlineASMColonStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
- IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
- IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
- static void enumeration(IO &IO,
- FormatStyle::BreakBinaryOperationsStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::BBO_Never);
- IO.enumCase(Value, "OnePerLine", FormatStyle::BBO_OnePerLine);
- IO.enumCase(Value, "RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
- }
-};
-
-template <> struct ScalarTraits<clang::tok::TokenKind> {
- static void output(const clang::tok::TokenKind &Value, void *,
- llvm::raw_ostream &Out) {
- if (const char *Spelling = clang::tok::getPunctuatorSpelling(Value))
- Out << Spelling;
- else
- Out << clang::tok::getTokenName(Value);
- }
-
- static StringRef input(StringRef Scalar, void *,
- clang::tok::TokenKind &Value) {
- // Map operator spelling strings to tok::TokenKind.
-#define PUNCTUATOR(Name, Spelling) \
- if (Scalar == Spelling) { \
- Value = clang::tok::Name; \
- return {}; \
- }
-#include "clang/Basic/TokenKinds.def"
- return "unknown operator";
- }
-
- static QuotingType mustQuote(StringRef) { return QuotingType::None; }
-};
-
-template <> struct MappingTraits<FormatStyle::BinaryOperationBreakRule> {
- static void mapping(IO &IO, FormatStyle::BinaryOperationBreakRule &Value) {
- IO.mapOptional("Operators", Value.Operators);
- // Default to OnePerLine since a per-operator rule with Never is a no-op.
- if (!IO.outputting())
- Value.Style = FormatStyle::BBO_OnePerLine;
- IO.mapOptional("Style", Value.Style);
- IO.mapOptional("MinChainLength", Value.MinChainLength);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::BreakBinaryOperationsOptions> {
- static void enumInput(IO &IO,
- FormatStyle::BreakBinaryOperationsOptions &Value) {
- IO.enumCase(Value, "Never",
- FormatStyle::BreakBinaryOperationsOptions(
- {FormatStyle::BBO_Never, {}}));
- IO.enumCase(Value, "OnePerLine",
- FormatStyle::BreakBinaryOperationsOptions(
- {FormatStyle::BBO_OnePerLine, {}}));
- IO.enumCase(Value, "RespectPrecedence",
- FormatStyle::BreakBinaryOperationsOptions(
- {FormatStyle::BBO_RespectPrecedence, {}}));
- }
-
- static void mapping(IO &IO,
- FormatStyle::BreakBinaryOperationsOptions &Value) {
- IO.mapOptional("Default", Value.Default);
- IO.mapOptional("PerOperator", Value.PerOperator);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
- static void
- enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
- IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
- IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
- IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
- IO.enumCase(Value, "AfterComma", FormatStyle::BCIS_AfterComma);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
- static void enumeration(IO &IO,
- FormatStyle::BreakInheritanceListStyle &Value) {
- IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
- IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
- IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
- IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
- static void enumeration(IO &IO,
- FormatStyle::BreakTemplateDeclarationsStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::BTDS_Leave);
- IO.enumCase(Value, "No", FormatStyle::BTDS_No);
- IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
- IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
- IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
- static void enumeration(IO &IO, FormatStyle::BracedListStyle &Value) {
- IO.enumCase(Value, "Block", FormatStyle::BLS_Block);
- IO.enumCase(Value, "FunctionCall", FormatStyle::BLS_FunctionCall);
- IO.enumCase(Value, "AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::BLS_Block);
- IO.enumCase(Value, "true", FormatStyle::BLS_AlignFirstComment);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
- static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value) {
- IO.enumCase(Value, "DontBreak", FormatStyle::DAS_DontBreak);
- IO.enumCase(Value, "BreakElements", FormatStyle::DAS_BreakElements);
- IO.enumCase(Value, "BreakAll", FormatStyle::DAS_BreakAll);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
- static void
- enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
- IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
- IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
- IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
- static void enumeration(IO &IO,
- FormatStyle::EscapedNewlineAlignmentStyle &Value) {
- IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
- IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
- IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
- IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
- IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
- static void
- enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
- IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
- IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<
- FormatStyle::EmptyLineBeforeAccessModifierStyle> {
- static void
- enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
- IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
- IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
- IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
- static void enumeration(IO &IO, FormatStyle::EnumTrailingCommaStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::ETC_Leave);
- IO.enumCase(Value, "Insert", FormatStyle::ETC_Insert);
- IO.enumCase(Value, "Remove", FormatStyle::ETC_Remove);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
- static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value) {
- IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
- IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
- IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
- IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
- IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
- static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base) {
- IO.mapOptional("Binary", Base.Binary);
- IO.mapOptional("BinaryMinDigitsInsert", Base.BinaryMinDigitsInsert);
- IO.mapOptional("BinaryMaxDigitsRemove", Base.BinaryMaxDigitsRemove);
- IO.mapOptional("Decimal", Base.Decimal);
- IO.mapOptional("DecimalMinDigitsInsert", Base.DecimalMinDigitsInsert);
- IO.mapOptional("DecimalMaxDigitsRemove", Base.DecimalMaxDigitsRemove);
- IO.mapOptional("Hex", Base.Hex);
- IO.mapOptional("HexMinDigitsInsert", Base.HexMinDigitsInsert);
- IO.mapOptional("HexMaxDigitsRemove", Base.HexMaxDigitsRemove);
-
- // For backward compatibility.
- IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigitsInsert);
- IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigitsInsert);
- IO.mapOptional("HexMinDigits", Base.HexMinDigitsInsert);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
- static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
- IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
- IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
- static void mapping(IO &IO, FormatStyle::KeepEmptyLinesStyle &Value) {
- IO.mapOptional("AtEndOfFile", Value.AtEndOfFile);
- IO.mapOptional("AtStartOfBlock", Value.AtStartOfBlock);
- IO.mapOptional("AtStartOfFile", Value.AtStartOfFile);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
- static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
- IO.enumCase(Value, "C", FormatStyle::LK_C);
- IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
- IO.enumCase(Value, "Java", FormatStyle::LK_Java);
- IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
- IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
- IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
- IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
- IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
- IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
- IO.enumCase(Value, "Json", FormatStyle::LK_Json);
- IO.enumCase(Value, "Verilog", FormatStyle::LK_Verilog);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
- static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
- IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
- IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
- IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
-
- IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
- IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
-
- IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
- IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
- IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
-
- IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
- IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
- IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
- static void enumeration(IO &IO,
- FormatStyle::LambdaBodyIndentationKind &Value) {
- IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
- IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
- static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value) {
- IO.enumCase(Value, "LF", FormatStyle::LE_LF);
- IO.enumCase(Value, "CRLF", FormatStyle::LE_CRLF);
- IO.enumCase(Value, "DeriveLF", FormatStyle::LE_DeriveLF);
- IO.enumCase(Value, "DeriveCRLF", FormatStyle::LE_DeriveCRLF);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
- static void enumeration(IO &IO,
- FormatStyle::NamespaceIndentationKind &Value) {
- IO.enumCase(Value, "None", FormatStyle::NI_None);
- IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
- IO.enumCase(Value, "All", FormatStyle::NI_All);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
- static void enumeration(IO &IO,
- FormatStyle::NumericLiteralComponentStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::NLCS_Leave);
- IO.enumCase(Value, "Upper", FormatStyle::NLCS_Upper);
- IO.enumCase(Value, "Lower", FormatStyle::NLCS_Lower);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
- static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &Value) {
- IO.mapOptional("ExponentLetter", Value.ExponentLetter);
- IO.mapOptional("HexDigit", Value.HexDigit);
- IO.mapOptional("Prefix", Value.Prefix);
- IO.mapOptional("Suffix", Value.Suffix);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
- static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value) {
- IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
- IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
- IO.enumCase(Value, "AlignAfterOperator",
- FormatStyle::OAS_AlignAfterOperator);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::OAS_Align);
- IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
- static void
- enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
- IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
- IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
- IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
- IO.enumCase(Value, "NextLineOnly", FormatStyle::PCIS_NextLineOnly);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
- static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
- IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
- IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
- IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::PAS_Left);
- IO.enumCase(Value, "false", FormatStyle::PAS_Right);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
- static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
- IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
- IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
- IO.enumCase(Value, "Leave", FormatStyle::PPDIS_Leave);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
- static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
- IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
- IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
- IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::RawStringFormat> {
- static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
- IO.mapOptional("Language", Format.Language);
- IO.mapOptional("Delimiters", Format.Delimiters);
- IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
- IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
- IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
- static void enumeration(IO &IO, FormatStyle::ReflowCommentsStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::RCS_Never);
- IO.enumCase(Value, "IndentOnly", FormatStyle::RCS_IndentOnly);
- IO.enumCase(Value, "Always", FormatStyle::RCS_Always);
- // For backward compatibility:
- IO.enumCase(Value, "false", FormatStyle::RCS_Never);
- IO.enumCase(Value, "true", FormatStyle::RCS_Always);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
- static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value) {
- IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
- IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
- IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
- IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
- static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::RPS_Leave);
- IO.enumCase(Value, "MultipleParentheses",
- FormatStyle::RPS_MultipleParentheses);
- IO.enumCase(Value, "ReturnStatement", FormatStyle::RPS_ReturnStatement);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
- static void enumeration(IO &IO,
- FormatStyle::RequiresClausePositionStyle &Value) {
- IO.enumCase(Value, "OwnLine", FormatStyle::RCPS_OwnLine);
- IO.enumCase(Value, "OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
- IO.enumCase(Value, "WithPreceding", FormatStyle::RCPS_WithPreceding);
- IO.enumCase(Value, "WithFollowing", FormatStyle::RCPS_WithFollowing);
- IO.enumCase(Value, "SingleLine", FormatStyle::RCPS_SingleLine);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
- static void
- enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value) {
- IO.enumCase(Value, "Keyword", FormatStyle::REI_Keyword);
- IO.enumCase(Value, "OuterScope", FormatStyle::REI_OuterScope);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
- static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::RTBS_None);
- IO.enumCase(Value, "Automatic", FormatStyle::RTBS_Automatic);
- IO.enumCase(Value, "ExceptShortType", FormatStyle::RTBS_ExceptShortType);
- IO.enumCase(Value, "All", FormatStyle::RTBS_All);
- IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
- IO.enumCase(Value, "TopLevelDefinitions",
- FormatStyle::RTBS_TopLevelDefinitions);
- IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
- static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
- IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
- IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
- static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
- IO.enumCase(Value, "false", FormatStyle::SBS_Never);
- IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
- IO.enumCase(Value, "true", FormatStyle::SBS_Always);
- IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::ShortFunctionStyle> {
- static void enumInput(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::ShortFunctionStyle());
- IO.enumCase(Value, "Empty",
- FormatStyle::ShortFunctionStyle::setEmptyOnly());
- IO.enumCase(Value, "Inline",
- FormatStyle::ShortFunctionStyle::setEmptyAndInline());
- IO.enumCase(Value, "InlineOnly",
- FormatStyle::ShortFunctionStyle::setInlineOnly());
- IO.enumCase(Value, "All", FormatStyle::ShortFunctionStyle::setAll());
-
- // For backward compatibility.
- IO.enumCase(Value, "true", FormatStyle::ShortFunctionStyle::setAll());
- IO.enumCase(Value, "false", FormatStyle::ShortFunctionStyle());
- }
-
- static void mapping(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
- IO.mapOptional("Empty", Value.Empty);
- IO.mapOptional("Inline", Value.Inline);
- IO.mapOptional("Other", Value.Other);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
- static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
- IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
- IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
- IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
-
- // For backward compatibility.
- IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
- IO.enumCase(Value, "false", FormatStyle::SIS_Never);
- IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
- static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::SLS_None);
- IO.enumCase(Value, "false", FormatStyle::SLS_None);
- IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
- IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
- IO.enumCase(Value, "All", FormatStyle::SLS_All);
- IO.enumCase(Value, "true", FormatStyle::SLS_All);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::ShortRecordStyle> {
- static void enumeration(IO &IO, FormatStyle::ShortRecordStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SRS_Never);
- IO.enumCase(Value, "EmptyAndAttached", FormatStyle::SRS_EmptyAndAttached);
- IO.enumCase(Value, "Empty", FormatStyle::SRS_Empty);
- IO.enumCase(Value, "Always", FormatStyle::SRS_Always);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::SortIncludesOptions> {
- static void enumInput(IO &IO, FormatStyle::SortIncludesOptions &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SortIncludesOptions{});
- IO.enumCase(Value, "CaseInsensitive",
- FormatStyle::SortIncludesOptions{/*Enabled=*/true,
- /*IgnoreCase=*/true,
- /*IgnoreExtension=*/false});
- IO.enumCase(Value, "CaseSensitive",
- FormatStyle::SortIncludesOptions{/*Enabled=*/true,
- /*IgnoreCase=*/false,
- /*IgnoreExtension=*/false});
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::SortIncludesOptions{});
- IO.enumCase(Value, "true",
- FormatStyle::SortIncludesOptions{/*Enabled=*/true,
- /*IgnoreCase=*/false,
- /*IgnoreExtension=*/false});
- }
-
- static void mapping(IO &IO, FormatStyle::SortIncludesOptions &Value) {
- IO.mapOptional("Enabled", Value.Enabled);
- IO.mapOptional("IgnoreCase", Value.IgnoreCase);
- IO.mapOptional("IgnoreExtension", Value.IgnoreExtension);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
- static void enumeration(IO &IO,
- FormatStyle::SortJavaStaticImportOptions &Value) {
- IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
- IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
- static void enumeration(IO &IO,
- FormatStyle::SortUsingDeclarationsOptions &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SUD_Never);
- IO.enumCase(Value, "Lexicographic", FormatStyle::SUD_Lexicographic);
- IO.enumCase(Value, "LexicographicNumeric",
- FormatStyle::SUD_LexicographicNumeric);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::SUD_Never);
- IO.enumCase(Value, "true", FormatStyle::SUD_LexicographicNumeric);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
- static void
- enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value) {
- IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
- IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
- IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
- IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
- static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
- IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
- IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
- IO.mapOptional("AfterFunctionDefinitionName",
- Spacing.AfterFunctionDefinitionName);
- IO.mapOptional("AfterFunctionDeclarationName",
- Spacing.AfterFunctionDeclarationName);
- IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
- IO.mapOptional("AfterNot", Spacing.AfterNot);
- IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
- IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
- IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
- IO.mapOptional("AfterRequiresInExpression",
- Spacing.AfterRequiresInExpression);
- IO.mapOptional("BeforeNonEmptyParentheses",
- Spacing.BeforeNonEmptyParentheses);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
- static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
- IO.enumCase(Value, "ControlStatements",
- FormatStyle::SBPO_ControlStatements);
- IO.enumCase(Value, "ControlStatementsExceptControlMacros",
- FormatStyle::SBPO_ControlStatementsExceptControlMacros);
- IO.enumCase(Value, "NonEmptyParentheses",
- FormatStyle::SBPO_NonEmptyParentheses);
- IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
- IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
- IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
- IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
- FormatStyle::SBPO_ControlStatementsExceptControlMacros);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
- static void enumeration(IO &IO, FormatStyle::SpaceInEmptyBracesStyle &Value) {
- IO.enumCase(Value, "Always", FormatStyle::SIEB_Always);
- IO.enumCase(Value, "Block", FormatStyle::SIEB_Block);
- IO.enumCase(Value, "Never", FormatStyle::SIEB_Never);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
- static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
- IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
- IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
- IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
- static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
- // Transform the maximum to signed, to parse "-1" correctly
- int signedMaximum = static_cast<int>(Space.Maximum);
- IO.mapOptional("Minimum", Space.Minimum);
- IO.mapOptional("Maximum", signedMaximum);
- Space.Maximum = static_cast<unsigned>(signedMaximum);
-
- if (Space.Maximum < std::numeric_limits<unsigned>::max())
- Space.Minimum = std::min(Space.Minimum, Space.Maximum);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {
- static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
- IO.mapOptional("ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
- IO.mapOptional("InCStyleCasts", Spaces.InCStyleCasts);
- IO.mapOptional("InConditionalStatements", Spaces.InConditionalStatements);
- IO.mapOptional("InEmptyParentheses", Spaces.InEmptyParentheses);
- IO.mapOptional("Other", Spaces.Other);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
- static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::SIPO_Never);
- IO.enumCase(Value, "Custom", FormatStyle::SIPO_Custom);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
- static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value) {
- IO.enumCase(Value, "None", FormatStyle::TCS_None);
- IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
- static void enumeration(IO &IO,
- FormatStyle::TrailingCommentsAlignmentKinds &Value) {
- IO.enumCase(Value, "Leave", FormatStyle::TCAS_Leave);
- IO.enumCase(Value, "Always", FormatStyle::TCAS_Always);
- IO.enumCase(Value, "Never", FormatStyle::TCAS_Never);
- }
-};
-
-template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
- static void enumInput(IO &IO,
- FormatStyle::TrailingCommentsAlignmentStyle &Value) {
- IO.enumCase(Value, "Leave",
- FormatStyle::TrailingCommentsAlignmentStyle(
- {FormatStyle::TCAS_Leave, 0, true}));
-
- IO.enumCase(Value, "Always",
- FormatStyle::TrailingCommentsAlignmentStyle(
- {FormatStyle::TCAS_Always, 0, true}));
-
- IO.enumCase(Value, "Never",
- FormatStyle::TrailingCommentsAlignmentStyle(
- {FormatStyle::TCAS_Never, 0, true}));
-
- // For backwards compatibility
- IO.enumCase(Value, "true",
- FormatStyle::TrailingCommentsAlignmentStyle(
- {FormatStyle::TCAS_Always, 0, true}));
- IO.enumCase(Value, "false",
- FormatStyle::TrailingCommentsAlignmentStyle(
- {FormatStyle::TCAS_Never, 0, true}));
- }
-
- static void mapping(IO &IO,
- FormatStyle::TrailingCommentsAlignmentStyle &Value) {
- IO.mapOptional("AlignPPAndNotPP", Value.AlignPPAndNotPP);
- IO.mapOptional("Kind", Value.Kind);
- IO.mapOptional("OverEmptyLines", Value.OverEmptyLines);
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
- static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::UT_Never);
- IO.enumCase(Value, "false", FormatStyle::UT_Never);
- IO.enumCase(Value, "Always", FormatStyle::UT_Always);
- IO.enumCase(Value, "true", FormatStyle::UT_Always);
- IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
- IO.enumCase(Value, "ForContinuationAndIndentation",
- FormatStyle::UT_ForContinuationAndIndentation);
- IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
- }
-};
-
-template <>
-struct ScalarEnumerationTraits<
- FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
- static void
- enumeration(IO &IO,
- FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value) {
- IO.enumCase(Value, "Never", FormatStyle::WNBWELS_Never);
- IO.enumCase(Value, "Always", FormatStyle::WNBWELS_Always);
- IO.enumCase(Value, "Leave", FormatStyle::WNBWELS_Leave);
- }
-};
-
-template <> struct MappingTraits<FormatStyle> {
- static void mapping(IO &IO, FormatStyle &Style) {
- // When reading, read the language first, we need it for getPredefinedStyle.
- IO.mapOptional("Language", Style.Language);
-
- StringRef BasedOnStyle;
- if (IO.outputting()) {
- StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
- "WebKit", "GNU", "Microsoft", "clang-format"};
- for (StringRef StyleName : Styles) {
- FormatStyle PredefinedStyle;
- if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
- Style == PredefinedStyle) {
- BasedOnStyle = StyleName;
- break;
- }
- }
- } else {
- IO.mapOptional("BasedOnStyle", BasedOnStyle);
- if (!BasedOnStyle.empty()) {
- FormatStyle::LanguageKind OldLanguage = Style.Language;
- FormatStyle::LanguageKind Language =
- ((FormatStyle *)IO.getContext())->Language;
- if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
- IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
- return;
- }
- Style.Language = OldLanguage;
- }
- }
-
- // Initialize some variables used in the parsing. The using logic is at the
- // end.
-
- // For backward compatibility:
- // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
- // false unless BasedOnStyle was Google or Chromium whereas that of
- // AllowAllConstructorInitializersOnNextLine was always true, so the
- // equivalent default value of PackConstructorInitializers is PCIS_NextLine
- // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
- // had a non-default value while PackConstructorInitializers has a default
- // value, set the latter to an equivalent non-default value if needed.
- const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive("google") ||
- BasedOnStyle.equals_insensitive("chromium");
- bool OnCurrentLine = IsGoogleOrChromium;
- bool OnNextLine = true;
-
- bool BreakBeforeInheritanceComma = false;
- bool BreakConstructorInitializersBeforeComma = false;
-
- bool DeriveLineEnding = true;
- bool UseCRLF = false;
-
- bool SpaceInEmptyBlock = false;
- bool SpaceInEmptyParentheses = false;
- bool SpacesInConditionalStatement = false;
- bool SpacesInCStyleCastParentheses = false;
- bool SpacesInParentheses = false;
-
- if (IO.outputting()) {
- IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
- } else {
- // For backward compatibility.
- BracketAlignmentStyle LocalBAS = BAS_Align;
- if (IsGoogleOrChromium) {
- FormatStyle::LanguageKind Language = Style.Language;
- if (Language == FormatStyle::LK_None)
- Language = ((FormatStyle *)IO.getContext())->Language;
- if (Language == FormatStyle::LK_JavaScript)
- LocalBAS = BAS_AlwaysBreak;
- else if (Language == FormatStyle::LK_Java)
- LocalBAS = BAS_DontAlign;
- } else if (BasedOnStyle.equals_insensitive("webkit")) {
- LocalBAS = BAS_DontAlign;
- }
- IO.mapOptional("AlignAfterOpenBracket", LocalBAS);
- Style.BreakAfterOpenBracketBracedList = false;
- Style.BreakAfterOpenBracketFunction = false;
- Style.BreakAfterOpenBracketIf = false;
- Style.BreakAfterOpenBracketLoop = false;
- Style.BreakAfterOpenBracketSwitch = false;
- Style.BreakBeforeCloseBracketBracedList = false;
- Style.BreakBeforeCloseBracketFunction = false;
- Style.BreakBeforeCloseBracketIf = false;
- Style.BreakBeforeCloseBracketLoop = false;
- Style.BreakBeforeCloseBracketSwitch = false;
-
- switch (LocalBAS) {
- case BAS_DontAlign:
- Style.AlignAfterOpenBracket = false;
- break;
- case BAS_BlockIndent:
- Style.BreakBeforeCloseBracketBracedList = true;
- Style.BreakBeforeCloseBracketFunction = true;
- Style.BreakBeforeCloseBracketIf = true;
- [[fallthrough]];
- case BAS_AlwaysBreak:
- Style.BreakAfterOpenBracketBracedList = true;
- Style.BreakAfterOpenBracketFunction = true;
- Style.BreakAfterOpenBracketIf = true;
- [[fallthrough]];
- case BAS_Align:
- Style.AlignAfterOpenBracket = true;
- break;
- }
- }
-
- // For backward compatibility.
- if (!IO.outputting()) {
- IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
- IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
- IO.mapOptional("AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
- IO.mapOptional("AlwaysBreakTemplateDeclarations",
- Style.BreakTemplateDeclarations);
- IO.mapOptional("BreakBeforeInheritanceComma",
- BreakBeforeInheritanceComma);
- IO.mapOptional("BreakConstructorInitializersBeforeComma",
- BreakConstructorInitializersBeforeComma);
- IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
- OnCurrentLine);
- IO.mapOptional("DeriveLineEnding", DeriveLineEnding);
- IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
- IO.mapOptional("KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
- IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
- Style.KeepEmptyLines.AtStartOfBlock);
- IO.mapOptional("IndentFunctionDeclarationAfterType",
- Style.IndentWrappedFunctionNames);
- IO.mapOptional("IndentRequires", Style.IndentRequiresClause);
- IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
- IO.mapOptional("SpaceAfterControlStatementKeyword",
- Style.SpaceBeforeParens);
- IO.mapOptional("SpaceInEmptyBlock", SpaceInEmptyBlock);
- IO.mapOptional("SpaceInEmptyParentheses", SpaceInEmptyParentheses);
- IO.mapOptional("SpacesInConditionalStatement",
- SpacesInConditionalStatement);
- IO.mapOptional("SpacesInCStyleCastParentheses",
- SpacesInCStyleCastParentheses);
- IO.mapOptional("SpacesInParentheses", SpacesInParentheses);
- IO.mapOptional("UseCRLF", UseCRLF);
- }
-
- IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
- IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
- IO.mapOptional("AlignConsecutiveAssignments",
- Style.AlignConsecutiveAssignments);
- IO.mapOptional("AlignConsecutiveBitFields",
- Style.AlignConsecutiveBitFields);
- IO.mapOptional("AlignConsecutiveDeclarations",
- Style.AlignConsecutiveDeclarations);
- IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
- IO.mapOptional("AlignConsecutiveShortCaseStatements",
- Style.AlignConsecutiveShortCaseStatements);
- IO.mapOptional("AlignConsecutiveTableGenBreakingDAGArgColons",
- Style.AlignConsecutiveTableGenBreakingDAGArgColons);
- IO.mapOptional("AlignConsecutiveTableGenCondOperatorColons",
- Style.AlignConsecutiveTableGenCondOperatorColons);
- IO.mapOptional("AlignConsecutiveTableGenDefinitionColons",
- Style.AlignConsecutiveTableGenDefinitionColons);
- IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
- IO.mapOptional("AlignOperands", Style.AlignOperands);
- IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
- IO.mapOptional("AllowAllArgumentsOnNextLine",
- Style.AllowAllArgumentsOnNextLine);
- IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
- Style.AllowAllParametersOfDeclarationOnNextLine);
- IO.mapOptional("AllowBreakBeforeNoexceptSpecifier",
- Style.AllowBreakBeforeNoexceptSpecifier);
- IO.mapOptional("AllowBreakBeforeQtProperty",
- Style.AllowBreakBeforeQtProperty);
- IO.mapOptional("AllowShortBlocksOnASingleLine",
- Style.AllowShortBlocksOnASingleLine);
- IO.mapOptional("AllowShortCaseExpressionOnASingleLine",
- Style.AllowShortCaseExpressionOnASingleLine);
- IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
- Style.AllowShortCaseLabelsOnASingleLine);
- IO.mapOptional("AllowShortCompoundRequirementOnASingleLine",
- Style.AllowShortCompoundRequirementOnASingleLine);
- IO.mapOptional("AllowShortEnumsOnASingleLine",
- Style.AllowShortEnumsOnASingleLine);
- IO.mapOptional("AllowShortFunctionsOnASingleLine",
- Style.AllowShortFunctionsOnASingleLine);
- IO.mapOptional("AllowShortIfStatementsOnASingleLine",
- Style.AllowShortIfStatementsOnASingleLine);
- IO.mapOptional("AllowShortLambdasOnASingleLine",
- Style.AllowShortLambdasOnASingleLine);
- IO.mapOptional("AllowShortLoopsOnASingleLine",
- Style.AllowShortLoopsOnASingleLine);
- IO.mapOptional("AllowShortNamespacesOnASingleLine",
- Style.AllowShortNamespacesOnASingleLine);
- IO.mapOptional("AllowShortRecordOnASingleLine",
- Style.AllowShortRecordOnASingleLine);
- IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
- Style.AlwaysBreakAfterDefinitionReturnType);
- IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
- Style.AlwaysBreakBeforeMultilineStrings);
- IO.mapOptional("AttributeMacros", Style.AttributeMacros);
- IO.mapOptional("BinPackArguments", Style.BinPackArguments);
- IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList);
- IO.mapOptional("BinPackParameters", Style.BinPackParameters);
- IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
- IO.mapOptional("BracedInitializerIndentWidth",
- Style.BracedInitializerIndentWidth);
- IO.mapOptional("BraceWrapping", Style.BraceWrapping);
- IO.mapOptional("BreakAdjacentStringLiterals",
- Style.BreakAdjacentStringLiterals);
- IO.mapOptional("BreakAfterAttributes", Style.BreakAfterAttributes);
- IO.mapOptional("BreakAfterJavaFieldAnnotations",
- Style.BreakAfterJavaFieldAnnotations);
- IO.mapOptional("BreakAfterOpenBracketBracedList",
- Style.BreakAfterOpenBracketBracedList);
- IO.mapOptional("BreakAfterOpenBracketFunction",
- Style.BreakAfterOpenBracketFunction);
- IO.mapOptional("BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
- IO.mapOptional("BreakAfterOpenBracketLoop",
- Style.BreakAfterOpenBracketLoop);
- IO.mapOptional("BreakAfterOpenBracketSwitch",
- Style.BreakAfterOpenBracketSwitch);
- IO.mapOptional("BreakAfterReturnType", Style.BreakAfterReturnType);
- IO.mapOptional("BreakArrays", Style.BreakArrays);
- IO.mapOptional("BreakBeforeBinaryOperators",
- Style.BreakBeforeBinaryOperators);
- IO.mapOptional("BreakBeforeCloseBracketBracedList",
- Style.BreakBeforeCloseBracketBracedList);
- IO.mapOptional("BreakBeforeCloseBracketFunction",
- Style.BreakBeforeCloseBracketFunction);
- IO.mapOptional("BreakBeforeCloseBracketIf",
- Style.BreakBeforeCloseBracketIf);
- IO.mapOptional("BreakBeforeCloseBracketLoop",
- Style.BreakBeforeCloseBracketLoop);
- IO.mapOptional("BreakBeforeCloseBracketSwitch",
- Style.BreakBeforeCloseBracketSwitch);
- IO.mapOptional("BreakBeforeConceptDeclarations",
- Style.BreakBeforeConceptDeclarations);
- IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
- IO.mapOptional("BreakBeforeInlineASMColon",
- Style.BreakBeforeInlineASMColon);
- IO.mapOptional("BreakBeforeTemplateCloser",
- Style.BreakBeforeTemplateCloser);
- IO.mapOptional("BreakBeforeTernaryOperators",
- Style.BreakBeforeTernaryOperators);
- IO.mapOptional("BreakBinaryOperations", Style.BreakBinaryOperations);
- IO.mapOptional("BreakConstructorInitializers",
- Style.BreakConstructorInitializers);
- IO.mapOptional("BreakFunctionDefinitionParameters",
- Style.BreakFunctionDefinitionParameters);
- IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
- IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
- IO.mapOptional("BreakTemplateDeclarations",
- Style.BreakTemplateDeclarations);
- IO.mapOptional("ColumnLimit", Style.ColumnLimit);
- IO.mapOptional("CommentPragmas", Style.CommentPragmas);
- IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
- IO.mapOptional("ConstructorInitializerIndentWidth",
- Style.ConstructorInitializerIndentWidth);
- IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
- IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
- IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
- IO.mapOptional("DisableFormat", Style.DisableFormat);
- IO.mapOptional("EmptyLineAfterAccessModifier",
- Style.EmptyLineAfterAccessModifier);
- IO.mapOptional("EmptyLineBeforeAccessModifier",
- Style.EmptyLineBeforeAccessModifier);
- IO.mapOptional("EnumTrailingComma", Style.EnumTrailingComma);
- IO.mapOptional("ExperimentalAutoDetectBinPacking",
- Style.ExperimentalAutoDetectBinPacking);
- IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
- IO.mapOptional("ForEachMacros", Style.ForEachMacros);
- IO.mapOptional("IfMacros", Style.IfMacros);
- IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
- IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
- IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
- IO.mapOptional("IncludeIsMainSourceRegex",
- Style.IncludeStyle.IncludeIsMainSourceRegex);
- IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
- IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
- IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
- IO.mapOptional("IndentExportBlock", Style.IndentExportBlock);
- IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
- IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
- IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
- IO.mapOptional("IndentRequiresClause", Style.IndentRequiresClause);
- IO.mapOptional("IndentWidth", Style.IndentWidth);
- IO.mapOptional("IndentWrappedFunctionNames",
- Style.IndentWrappedFunctionNames);
- IO.mapOptional("InsertBraces", Style.InsertBraces);
- IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
- IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
- IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
- IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
- IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
- IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
- IO.mapOptional("KeepEmptyLines", Style.KeepEmptyLines);
- IO.mapOptional("KeepFormFeed", Style.KeepFormFeed);
- IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
- IO.mapOptional("LineEnding", Style.LineEnding);
- IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
- IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
- IO.mapOptional("Macros", Style.Macros);
- IO.mapOptional("MacrosSkippedByRemoveParentheses",
- Style.MacrosSkippedByRemoveParentheses);
- IO.mapOptional("MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
- IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
- IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
- IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
- IO.mapOptional("NumericLiteralCase", Style.NumericLiteralCase);
- IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
- IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
- IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
- Style.ObjCBreakBeforeNestedBlockParam);
- IO.mapOptional("ObjCPropertyAttributeOrder",
- Style.ObjCPropertyAttributeOrder);
- IO.mapOptional("ObjCSpaceAfterMethodDeclarationPrefix",
- Style.ObjCSpaceAfterMethodDeclarationPrefix);
- IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
- IO.mapOptional("ObjCSpaceBeforeProtocolList",
- Style.ObjCSpaceBeforeProtocolList);
- IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
- IO.mapOptional("PackConstructorInitializers",
- Style.PackConstructorInitializers);
- IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
- IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
- Style.PenaltyBreakBeforeFirstCallParameter);
- IO.mapOptional("PenaltyBreakBeforeMemberAccess",
- Style.PenaltyBreakBeforeMemberAccess);
- IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
- IO.mapOptional("PenaltyBreakFirstLessLess",
- Style.PenaltyBreakFirstLessLess);
- IO.mapOptional("PenaltyBreakOpenParenthesis",
- Style.PenaltyBreakOpenParenthesis);
- IO.mapOptional("PenaltyBreakScopeResolution",
- Style.PenaltyBreakScopeResolution);
- IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
- IO.mapOptional("PenaltyBreakTemplateDeclaration",
- Style.PenaltyBreakTemplateDeclaration);
- IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
- IO.mapOptional("PenaltyIndentedWhitespace",
- Style.PenaltyIndentedWhitespace);
- IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
- Style.PenaltyReturnTypeOnItsOwnLine);
- IO.mapOptional("PointerAlignment", Style.PointerAlignment);
- IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
- IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
- // Default Order for Left/Right based Qualifier alignment.
- if (Style.QualifierAlignment == FormatStyle::QAS_Right)
- Style.QualifierOrder = {"type", "const", "volatile"};
- else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
- Style.QualifierOrder = {"const", "volatile", "type"};
- else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
- IO.mapOptional("QualifierOrder", Style.QualifierOrder);
- IO.mapOptional("RawStringFormats", Style.RawStringFormats);
- IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
- IO.mapOptional("ReflowComments", Style.ReflowComments);
- IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
- IO.mapOptional("RemoveEmptyLinesInUnwrappedLines",
- Style.RemoveEmptyLinesInUnwrappedLines);
- IO.mapOptional("RemoveParentheses", Style.RemoveParentheses);
- IO.mapOptional("RemoveSemicolon", Style.RemoveSemicolon);
- IO.mapOptional("RequiresClausePosition", Style.RequiresClausePosition);
- IO.mapOptional("RequiresExpressionIndentation",
- Style.RequiresExpressionIndentation);
- IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
- IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
- IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
- IO.mapOptional("SortIncludes", Style.SortIncludes);
- IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
- IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
- IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
- IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
- IO.mapOptional("SpaceAfterOperatorKeyword",
- Style.SpaceAfterOperatorKeyword);
- IO.mapOptional("SpaceAfterTemplateKeyword",
- Style.SpaceAfterTemplateKeyword);
- IO.mapOptional("SpaceAroundPointerQualifiers",
- Style.SpaceAroundPointerQualifiers);
- IO.mapOptional("SpaceBeforeAssignmentOperators",
- Style.SpaceBeforeAssignmentOperators);
- IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
- IO.mapOptional("SpaceBeforeCpp11BracedList",
- Style.SpaceBeforeCpp11BracedList);
- IO.mapOptional("SpaceBeforeCtorInitializerColon",
- Style.SpaceBeforeCtorInitializerColon);
- IO.mapOptional("SpaceBeforeInheritanceColon",
- Style.SpaceBeforeInheritanceColon);
- IO.mapOptional("SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
- IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
- IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
- IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
- Style.SpaceBeforeRangeBasedForLoopColon);
- IO.mapOptional("SpaceBeforeSquareBrackets",
- Style.SpaceBeforeSquareBrackets);
- IO.mapOptional("SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
- IO.mapOptional("SpacesBeforeTrailingComments",
- Style.SpacesBeforeTrailingComments);
- IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
- IO.mapOptional("SpacesInContainerLiterals",
- Style.SpacesInContainerLiterals);
- IO.mapOptional("SpacesInLineCommentPrefix",
- Style.SpacesInLineCommentPrefix);
- IO.mapOptional("SpacesInParens", Style.SpacesInParens);
- IO.mapOptional("SpacesInParensOptions", Style.SpacesInParensOptions);
- IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
- IO.mapOptional("Standard", Style.Standard);
- IO.mapOptional("StatementAttributeLikeMacros",
- Style.StatementAttributeLikeMacros);
- IO.mapOptional("StatementMacros", Style.StatementMacros);
- IO.mapOptional("TableGenBreakingDAGArgOperators",
- Style.TableGenBreakingDAGArgOperators);
- IO.mapOptional("TableGenBreakInsideDAGArg",
- Style.TableGenBreakInsideDAGArg);
- IO.mapOptional("TabWidth", Style.TabWidth);
- IO.mapOptional("TemplateNames", Style.TemplateNames);
- IO.mapOptional("TypeNames", Style.TypeNames);
- IO.mapOptional("TypenameMacros", Style.TypenameMacros);
- IO.mapOptional("UseTab", Style.UseTab);
- IO.mapOptional("VariableTemplates", Style.VariableTemplates);
- IO.mapOptional("VerilogBreakBetweenInstancePorts",
- Style.VerilogBreakBetweenInstancePorts);
- IO.mapOptional("WhitespaceSensitiveMacros",
- Style.WhitespaceSensitiveMacros);
- IO.mapOptional("WrapNamespaceBodyWithEmptyLines",
- Style.WrapNamespaceBodyWithEmptyLines);
-
- // If AlwaysBreakAfterDefinitionReturnType was specified but
- // BreakAfterReturnType was not, initialize the latter from the former for
- // backwards compatibility.
- if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
- Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
- if (Style.AlwaysBreakAfterDefinitionReturnType ==
- FormatStyle::DRTBS_All) {
- Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
- } else if (Style.AlwaysBreakAfterDefinitionReturnType ==
- FormatStyle::DRTBS_TopLevel) {
- Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
- }
- }
-
- // If BreakBeforeInheritanceComma was specified but BreakInheritance was
- // not, initialize the latter from the former for backwards compatibility.
- if (BreakBeforeInheritanceComma &&
- Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
- Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
- }
-
- // If BreakConstructorInitializersBeforeComma was specified but
- // BreakConstructorInitializers was not, initialize the latter from the
- // former for backwards compatibility.
- if (BreakConstructorInitializersBeforeComma &&
- Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- }
-
- if (!IsGoogleOrChromium) {
- if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
- OnCurrentLine) {
- Style.PackConstructorInitializers = OnNextLine
- ? FormatStyle::PCIS_NextLine
- : FormatStyle::PCIS_CurrentLine;
- }
- } else if (Style.PackConstructorInitializers ==
- FormatStyle::PCIS_NextLine) {
- if (!OnCurrentLine)
- Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
- else if (!OnNextLine)
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- }
-
- if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
- if (!DeriveLineEnding)
- Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
- else if (UseCRLF)
- Style.LineEnding = FormatStyle::LE_DeriveCRLF;
- }
-
- // If SpaceInEmptyBlock was specified but SpaceInEmptyBraces was not,
- // initialize the latter from the former for backward compatibility.
- if (SpaceInEmptyBlock &&
- Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
- Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
- }
-
- if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
- (SpacesInParentheses || SpaceInEmptyParentheses ||
- SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
- if (SpacesInParentheses) {
- // For backward compatibility.
- Style.SpacesInParensOptions.ExceptDoubleParentheses = false;
- Style.SpacesInParensOptions.InConditionalStatements = true;
- Style.SpacesInParensOptions.InCStyleCasts =
- SpacesInCStyleCastParentheses;
- Style.SpacesInParensOptions.InEmptyParentheses =
- SpaceInEmptyParentheses;
- Style.SpacesInParensOptions.Other = true;
- } else {
- Style.SpacesInParensOptions = {};
- Style.SpacesInParensOptions.InConditionalStatements =
- SpacesInConditionalStatement;
- Style.SpacesInParensOptions.InCStyleCasts =
- SpacesInCStyleCastParentheses;
- Style.SpacesInParensOptions.InEmptyParentheses =
- SpaceInEmptyParentheses;
- }
- Style.SpacesInParens = FormatStyle::SIPO_Custom;
- }
- }
-};
-
-// Allows to read vector<FormatStyle> while keeping default values.
-// IO.getContext() should contain a pointer to the FormatStyle structure, that
-// will be used to get default values for missing keys.
-// If the first element has no Language specified, it will be treated as the
-// default one for the following elements.
-template <> struct DocumentListTraits<std::vector<FormatStyle>> {
- static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
- return Seq.size();
- }
- static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
- size_t Index) {
- if (Index >= Seq.size()) {
- assert(Index == Seq.size());
- FormatStyle Template;
- if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
- Template = Seq[0];
- } else {
- Template = *((const FormatStyle *)IO.getContext());
- Template.Language = FormatStyle::LK_None;
- }
- Seq.resize(Index + 1, Template);
- }
- return Seq[Index];
- }
-};
-
-template <> struct ScalarEnumerationTraits<FormatStyle::IndentGotoLabelStyle> {
- static void enumeration(IO &IO, FormatStyle::IndentGotoLabelStyle &Value) {
- IO.enumCase(Value, "NoIndent", FormatStyle::IGLS_NoIndent);
- IO.enumCase(Value, "OuterIndent", FormatStyle::IGLS_OuterIndent);
- IO.enumCase(Value, "InnerIndent", FormatStyle::IGLS_InnerIndent);
- IO.enumCase(Value, "HalfIndent", FormatStyle::IGLS_HalfIndent);
-
- // For backward compatibility.
- IO.enumCase(Value, "false", FormatStyle::IGLS_NoIndent);
- IO.enumCase(Value, "true", FormatStyle::IGLS_OuterIndent);
- }
-};
-
-} // namespace yaml
-} // namespace llvm
-
-namespace clang {
-namespace format {
-
-const std::error_category &getParseCategory() {
- static const ParseErrorCategory C{};
- return C;
-}
-std::error_code make_error_code(ParseError e) {
- return std::error_code(static_cast<int>(e), getParseCategory());
-}
-
-inline llvm::Error make_string_error(const Twine &Message) {
- return llvm::make_error<llvm::StringError>(Message,
- llvm::inconvertibleErrorCode());
-}
-
-const char *ParseErrorCategory::name() const noexcept {
- return "clang-format.parse_error";
-}
-
-std::string ParseErrorCategory::message(int EV) const {
- switch (static_cast<ParseError>(EV)) {
- case ParseError::Success:
- return "Success";
- case ParseError::Error:
- return "Invalid argument";
- case ParseError::Unsuitable:
- return "Unsuitable";
- case ParseError::BinPackTrailingCommaConflict:
- return "trailing comma insertion cannot be used with bin packing";
- case ParseError::InvalidQualifierSpecified:
- return "Invalid qualifier specified in QualifierOrder";
- case ParseError::DuplicateQualifierSpecified:
- return "Duplicate qualifier specified in QualifierOrder";
- case ParseError::MissingQualifierType:
- return "Missing type in QualifierOrder";
- case ParseError::MissingQualifierOrder:
- return "Missing QualifierOrder";
- }
- llvm_unreachable("unexpected parse error");
-}
-
-static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
- if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
- return;
- Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
- /*AfterClass=*/false,
- /*AfterControlStatement=*/FormatStyle::BWACS_Never,
- /*AfterEnum=*/false,
- /*AfterFunction=*/false,
- /*AfterNamespace=*/false,
- /*AfterObjCDeclaration=*/false,
- /*AfterStruct=*/false,
- /*AfterUnion=*/false,
- /*AfterExternBlock=*/false,
- /*BeforeCatch=*/false,
- /*BeforeElse=*/false,
- /*BeforeLambdaBody=*/false,
- /*BeforeWhile=*/false,
- /*IndentBraces=*/false,
- /*SplitEmptyFunction=*/true,
- /*SplitEmptyRecord=*/true,
- /*SplitEmptyNamespace=*/true};
- switch (Expanded.BreakBeforeBraces) {
- case FormatStyle::BS_Linux:
- Expanded.BraceWrapping.AfterClass = true;
- Expanded.BraceWrapping.AfterFunction = true;
- Expanded.BraceWrapping.AfterNamespace = true;
- break;
- case FormatStyle::BS_Mozilla:
- Expanded.BraceWrapping.AfterClass = true;
- Expanded.BraceWrapping.AfterEnum = true;
- Expanded.BraceWrapping.AfterFunction = true;
- Expanded.BraceWrapping.AfterStruct = true;
- Expanded.BraceWrapping.AfterUnion = true;
- Expanded.BraceWrapping.AfterExternBlock = true;
- Expanded.BraceWrapping.SplitEmptyFunction = true;
- Expanded.BraceWrapping.SplitEmptyRecord = false;
- break;
- case FormatStyle::BS_Stroustrup:
- Expanded.BraceWrapping.AfterFunction = true;
- Expanded.BraceWrapping.BeforeCatch = true;
- Expanded.BraceWrapping.BeforeElse = true;
- break;
- case FormatStyle::BS_Allman:
- Expanded.BraceWrapping.AfterCaseLabel = true;
- Expanded.BraceWrapping.AfterClass = true;
- Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- Expanded.BraceWrapping.AfterEnum = true;
- Expanded.BraceWrapping.AfterFunction = true;
- Expanded.BraceWrapping.AfterNamespace = true;
- Expanded.BraceWrapping.AfterObjCDeclaration = true;
- Expanded.BraceWrapping.AfterStruct = true;
- Expanded.BraceWrapping.AfterUnion = true;
- Expanded.BraceWrapping.AfterExternBlock = true;
- Expanded.BraceWrapping.BeforeCatch = true;
- Expanded.BraceWrapping.BeforeElse = true;
- Expanded.BraceWrapping.BeforeLambdaBody = true;
- break;
- case FormatStyle::BS_Whitesmiths:
- Expanded.BraceWrapping.AfterCaseLabel = true;
- Expanded.BraceWrapping.AfterClass = true;
- Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- Expanded.BraceWrapping.AfterEnum = true;
- Expanded.BraceWrapping.AfterFunction = true;
- Expanded.BraceWrapping.AfterNamespace = true;
- Expanded.BraceWrapping.AfterObjCDeclaration = true;
- Expanded.BraceWrapping.AfterStruct = true;
- Expanded.BraceWrapping.AfterExternBlock = true;
- Expanded.BraceWrapping.BeforeCatch = true;
- Expanded.BraceWrapping.BeforeElse = true;
- Expanded.BraceWrapping.BeforeLambdaBody = true;
- break;
- case FormatStyle::BS_GNU:
- Expanded.BraceWrapping = {
- /*AfterCaseLabel=*/true,
- /*AfterClass=*/true,
- /*AfterControlStatement=*/FormatStyle::BWACS_Always,
- /*AfterEnum=*/true,
- /*AfterFunction=*/true,
- /*AfterNamespace=*/true,
- /*AfterObjCDeclaration=*/true,
- /*AfterStruct=*/true,
- /*AfterUnion=*/true,
- /*AfterExternBlock=*/true,
- /*BeforeCatch=*/true,
- /*BeforeElse=*/true,
- /*BeforeLambdaBody=*/true,
- /*BeforeWhile=*/true,
- /*IndentBraces=*/true,
- /*SplitEmptyFunction=*/true,
- /*SplitEmptyRecord=*/true,
- /*SplitEmptyNamespace=*/true};
- break;
- case FormatStyle::BS_WebKit:
- Expanded.BraceWrapping.AfterFunction = true;
- break;
- default:
- break;
- }
-}
-
-static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded) {
- if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
- return;
- // Reset all flags
- Expanded.SpaceBeforeParensOptions = {};
- Expanded.SpaceBeforeParensOptions.AfterPlacementOperator = true;
-
- switch (Expanded.SpaceBeforeParens) {
- case FormatStyle::SBPO_ControlStatements:
- Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
- Expanded.SpaceBeforeParensOptions.AfterForeachMacros = true;
- Expanded.SpaceBeforeParensOptions.AfterIfMacros = true;
- break;
- case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
- Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
- break;
- case FormatStyle::SBPO_NonEmptyParentheses:
- Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
- break;
- default:
- break;
- }
-}
-
-static void expandPresetsSpacesInParens(FormatStyle &Expanded) {
- if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
- return;
- assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
- // Reset all flags
- Expanded.SpacesInParensOptions = {};
-}
-
-FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
- FormatStyle LLVMStyle;
- LLVMStyle.AccessModifierOffset = -2;
- LLVMStyle.AlignAfterOpenBracket = true;
- LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
- LLVMStyle.AlignConsecutiveAssignments = {};
- LLVMStyle.AlignConsecutiveAssignments.PadOperators = true;
- LLVMStyle.AlignConsecutiveBitFields = {};
- LLVMStyle.AlignConsecutiveDeclarations = {};
- LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations = true;
- LLVMStyle.AlignConsecutiveMacros = {};
- LLVMStyle.AlignConsecutiveShortCaseStatements = {};
- LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
- LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
- LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
- LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
- LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
- LLVMStyle.AlignTrailingComments = {};
- LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
- LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
- LLVMStyle.AlignTrailingComments.AlignPPAndNotPP = true;
- LLVMStyle.AllowAllArgumentsOnNextLine = true;
- LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
- LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
- LLVMStyle.AllowBreakBeforeQtProperty = false;
- LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
- LLVMStyle.AllowShortCaseExpressionOnASingleLine = true;
- LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
- LLVMStyle.AllowShortCompoundRequirementOnASingleLine = true;
- LLVMStyle.AllowShortEnumsOnASingleLine = true;
- LLVMStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
- LLVMStyle.AllowShortLoopsOnASingleLine = false;
- LLVMStyle.AllowShortNamespacesOnASingleLine = false;
- LLVMStyle.AllowShortRecordOnASingleLine = FormatStyle::SRS_EmptyAndAttached;
- LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
- LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
- LLVMStyle.AttributeMacros.push_back("__capability");
- LLVMStyle.BinPackArguments = true;
- LLVMStyle.BinPackLongBracedList = true;
- LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
- LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
- LLVMStyle.BracedInitializerIndentWidth = -1;
- LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
- /*AfterClass=*/false,
- /*AfterControlStatement=*/FormatStyle::BWACS_Never,
- /*AfterEnum=*/false,
- /*AfterFunction=*/false,
- /*AfterNamespace=*/false,
- /*AfterObjCDeclaration=*/false,
- /*AfterStruct=*/false,
- /*AfterUnion=*/false,
- /*AfterExternBlock=*/false,
- /*BeforeCatch=*/false,
- /*BeforeElse=*/false,
- /*BeforeLambdaBody=*/false,
- /*BeforeWhile=*/false,
- /*IndentBraces=*/false,
- /*SplitEmptyFunction=*/true,
- /*SplitEmptyRecord=*/true,
- /*SplitEmptyNamespace=*/true};
- LLVMStyle.BreakAdjacentStringLiterals = true;
- LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
- LLVMStyle.BreakAfterJavaFieldAnnotations = false;
- LLVMStyle.BreakAfterOpenBracketBracedList = false;
- LLVMStyle.BreakAfterOpenBracketFunction = false;
- LLVMStyle.BreakAfterOpenBracketIf = false;
- LLVMStyle.BreakAfterOpenBracketLoop = false;
- LLVMStyle.BreakAfterOpenBracketSwitch = false;
- LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
- LLVMStyle.BreakArrays = true;
- LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
- LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
- LLVMStyle.BreakBeforeCloseBracketBracedList = false;
- LLVMStyle.BreakBeforeCloseBracketFunction = false;
- LLVMStyle.BreakBeforeCloseBracketIf = false;
- LLVMStyle.BreakBeforeCloseBracketLoop = false;
- LLVMStyle.BreakBeforeCloseBracketSwitch = false;
- LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
- LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
- LLVMStyle.BreakBeforeTemplateCloser = false;
- LLVMStyle.BreakBeforeTernaryOperators = true;
- LLVMStyle.BreakBinaryOperations = {FormatStyle::BBO_Never, {}};
- LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
- LLVMStyle.BreakFunctionDefinitionParameters = false;
- LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
- LLVMStyle.BreakStringLiterals = true;
- LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
- LLVMStyle.ColumnLimit = 80;
- LLVMStyle.CommentPragmas = "^ IWYU pragma:";
- LLVMStyle.CompactNamespaces = false;
- LLVMStyle.ConstructorInitializerIndentWidth = 4;
- LLVMStyle.ContinuationIndentWidth = 4;
- LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
- LLVMStyle.DerivePointerAlignment = false;
- LLVMStyle.DisableFormat = false;
- LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
- LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
- LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
- LLVMStyle.ExperimentalAutoDetectBinPacking = false;
- LLVMStyle.FixNamespaceComments = true;
- LLVMStyle.ForEachMacros.push_back("foreach");
- LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
- LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
- LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
- LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
- LLVMStyle.IncludeStyle.IncludeCategories = {
- {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
- {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
- {".*", 1, 0, false}};
- LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
- LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
- LLVMStyle.IndentAccessModifiers = false;
- LLVMStyle.IndentCaseBlocks = false;
- LLVMStyle.IndentCaseLabels = false;
- LLVMStyle.IndentExportBlock = true;
- LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
- LLVMStyle.IndentGotoLabels = FormatStyle::IGLS_OuterIndent;
- LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
- LLVMStyle.IndentRequiresClause = true;
- LLVMStyle.IndentWidth = 2;
- LLVMStyle.IndentWrappedFunctionNames = false;
- LLVMStyle.InsertBraces = false;
- LLVMStyle.InsertNewlineAtEOF = false;
- LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
- LLVMStyle.IntegerLiteralSeparator = {};
- LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
- LLVMStyle.JavaScriptWrapImports = true;
- LLVMStyle.KeepEmptyLines = {
- /*AtEndOfFile=*/false,
- /*AtStartOfBlock=*/true,
- /*AtStartOfFile=*/true,
- };
- LLVMStyle.KeepFormFeed = false;
- LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
- LLVMStyle.Language = Language;
- LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
- LLVMStyle.MaxEmptyLinesToKeep = 1;
- LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
- LLVMStyle.NumericLiteralCase = {/*ExponentLetter=*/FormatStyle::NLCS_Leave,
- /*HexDigit=*/FormatStyle::NLCS_Leave,
- /*Prefix=*/FormatStyle::NLCS_Leave,
- /*Suffix=*/FormatStyle::NLCS_Leave};
- LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
- LLVMStyle.ObjCBlockIndentWidth = 2;
- LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
- LLVMStyle.ObjCSpaceAfterMethodDeclarationPrefix = true;
- LLVMStyle.ObjCSpaceAfterProperty = false;
- LLVMStyle.ObjCSpaceBeforeProtocolList = true;
- LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
- LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
- LLVMStyle.PPIndentWidth = -1;
- LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
- LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
- LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
- LLVMStyle.RemoveBracesLLVM = false;
- LLVMStyle.RemoveEmptyLinesInUnwrappedLines = false;
- LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
- LLVMStyle.RemoveSemicolon = false;
- LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
- LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
- LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
- LLVMStyle.ShortNamespaceLines = 1;
- LLVMStyle.SkipMacroDefinitionBody = false;
- LLVMStyle.SortIncludes = {/*Enabled=*/true, /*IgnoreCase=*/false,
- /*IgnoreExtension=*/false};
- LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
- LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
- LLVMStyle.SpaceAfterCStyleCast = false;
- LLVMStyle.SpaceAfterLogicalNot = false;
- LLVMStyle.SpaceAfterOperatorKeyword = false;
- LLVMStyle.SpaceAfterTemplateKeyword = true;
- LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
- LLVMStyle.SpaceBeforeAssignmentOperators = true;
- LLVMStyle.SpaceBeforeCaseColon = false;
- LLVMStyle.SpaceBeforeCpp11BracedList = false;
- LLVMStyle.SpaceBeforeCtorInitializerColon = true;
- LLVMStyle.SpaceBeforeInheritanceColon = true;
- LLVMStyle.SpaceBeforeJsonColon = false;
- LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
- LLVMStyle.SpaceBeforeParensOptions = {};
- LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements = true;
- LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros = true;
- LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
- LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
- LLVMStyle.SpaceBeforeSquareBrackets = false;
- LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
- LLVMStyle.SpacesBeforeTrailingComments = 1;
- LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
- LLVMStyle.SpacesInContainerLiterals = true;
- LLVMStyle.SpacesInLineCommentPrefix = {
- /*Minimum=*/1, /*Maximum=*/std::numeric_limits<unsigned>::max()};
- LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
- LLVMStyle.SpacesInSquareBrackets = false;
- LLVMStyle.Standard = FormatStyle::LS_Latest;
- LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
- LLVMStyle.StatementMacros.push_back("Q_UNUSED");
- LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
- LLVMStyle.TableGenBreakingDAGArgOperators = {};
- LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
- LLVMStyle.TabWidth = 8;
- LLVMStyle.UseTab = FormatStyle::UT_Never;
- LLVMStyle.VerilogBreakBetweenInstancePorts = true;
- LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
- LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
- LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
- LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
- LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
- LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
-
- LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
- LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
- LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
- LLVMStyle.PenaltyBreakComment = 300;
- LLVMStyle.PenaltyBreakFirstLessLess = 120;
- LLVMStyle.PenaltyBreakOpenParenthesis = 0;
- LLVMStyle.PenaltyBreakScopeResolution = 500;
- LLVMStyle.PenaltyBreakString = 1000;
- LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
- LLVMStyle.PenaltyExcessCharacter = 1'000'000;
- LLVMStyle.PenaltyIndentedWhitespace = 0;
- LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
-
- // Defaults that differ when not C++.
- switch (Language) {
- case FormatStyle::LK_TableGen:
- LLVMStyle.SpacesInContainerLiterals = false;
- break;
- case FormatStyle::LK_Json:
- LLVMStyle.ColumnLimit = 0;
- break;
- case FormatStyle::LK_Verilog:
- LLVMStyle.IndentCaseLabels = true;
- LLVMStyle.SpacesInContainerLiterals = false;
- break;
- default:
- break;
- }
-
- return LLVMStyle;
-}
-
-FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
- if (Language == FormatStyle::LK_TextProto) {
- FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
- GoogleStyle.Language = FormatStyle::LK_TextProto;
-
- return GoogleStyle;
- }
-
- FormatStyle GoogleStyle = getLLVMStyle(Language);
-
- GoogleStyle.AccessModifierOffset = -1;
- GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- GoogleStyle.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- GoogleStyle.AllowShortLoopsOnASingleLine = true;
- GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
- // Abseil aliases to clang's `_Nonnull`, `_Nullable` and `_Null_unspecified`.
- GoogleStyle.AttributeMacros.push_back("absl_nonnull");
- GoogleStyle.AttributeMacros.push_back("absl_nullable");
- GoogleStyle.AttributeMacros.push_back("absl_nullability_unknown");
- GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
- GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
- GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
- {"^<.*\\.h>", 1, 0, false},
- {"^<.*", 2, 0, false},
- {".*", 3, 0, false}};
- GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
- GoogleStyle.IndentCaseLabels = true;
- GoogleStyle.KeepEmptyLines.AtStartOfBlock = false;
- GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
- GoogleStyle.ObjCSpaceAfterProperty = false;
- GoogleStyle.ObjCSpaceBeforeProtocolList = true;
- GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
- GoogleStyle.RawStringFormats = {
- {
- FormatStyle::LK_Cpp,
- /*Delimiters=*/
- {
- "cc",
- "CC",
- "cpp",
- "Cpp",
- "CPP",
- "c++",
- "C++",
- },
- /*EnclosingFunctionNames=*/
- {},
- /*CanonicalDelimiter=*/"",
- /*BasedOnStyle=*/"google",
- },
- {
- FormatStyle::LK_TextProto,
- /*Delimiters=*/
- {
- "pb",
- "PB",
- "proto",
- "PROTO",
- },
- /*EnclosingFunctionNames=*/
- {
- "EqualsProto",
- "EquivToProto",
- "PARSE_PARTIAL_TEXT_PROTO",
- "PARSE_TEST_PROTO",
- "PARSE_TEXT_PROTO",
- "ParseTextOrDie",
- "ParseTextProtoOrDie",
- "ParseTestProto",
- "ParsePartialTestProto",
- },
- /*CanonicalDelimiter=*/"pb",
- /*BasedOnStyle=*/"google",
- },
- };
-
- GoogleStyle.SpacesBeforeTrailingComments = 2;
- GoogleStyle.Standard = FormatStyle::LS_Auto;
-
- GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
- GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
-
- if (Language == FormatStyle::LK_Java) {
- GoogleStyle.AlignAfterOpenBracket = false;
- GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
- GoogleStyle.AlignTrailingComments = {};
- GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
- GoogleStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
- GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- GoogleStyle.ColumnLimit = 100;
- GoogleStyle.SpaceAfterCStyleCast = true;
- GoogleStyle.SpacesBeforeTrailingComments = 1;
- } else if (Language == FormatStyle::LK_JavaScript) {
- GoogleStyle.BreakAfterOpenBracketBracedList = true;
- GoogleStyle.BreakAfterOpenBracketFunction = true;
- GoogleStyle.BreakAfterOpenBracketIf = true;
- GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
- GoogleStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- // TODO: still under discussion whether to switch to SLS_All.
- GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
- GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
- GoogleStyle.BreakBeforeTernaryOperators = false;
- // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
- // commonly followed by overlong URLs.
- GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
- // TODO: enable once decided, in particular re disabling bin packing.
- // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
- // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
- GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
- GoogleStyle.JavaScriptWrapImports = false;
- GoogleStyle.MaxEmptyLinesToKeep = 3;
- GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
- GoogleStyle.SpacesInContainerLiterals = false;
- } else if (Language == FormatStyle::LK_Proto) {
- GoogleStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
- // This affects protocol buffer options specifications and text protos.
- // Text protos are currently mostly formatted inside C++ raw string literals
- // and often the current breaking behavior of string literals is not
- // beneficial there. Investigate turning this on once proper string reflow
- // has been implemented.
- GoogleStyle.BreakStringLiterals = false;
- GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
- GoogleStyle.SpacesInContainerLiterals = false;
- } else if (Language == FormatStyle::LK_ObjC) {
- GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
- GoogleStyle.ColumnLimit = 100;
- GoogleStyle.DerivePointerAlignment = true;
- // "Regroup" doesn't work well for ObjC yet (main header heuristic,
- // relationship between ObjC standard library headers and other heades,
- // #imports, etc.)
- GoogleStyle.IncludeStyle.IncludeBlocks =
- tooling::IncludeStyle::IBS_Preserve;
- } else if (Language == FormatStyle::LK_CSharp) {
- GoogleStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- GoogleStyle.BreakStringLiterals = false;
- GoogleStyle.ColumnLimit = 100;
- GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
- }
-
- return GoogleStyle;
-}
-
-FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
- FormatStyle ChromiumStyle = getGoogleStyle(Language);
-
- // Disable include reordering across blocks in Chromium code.
- // - clang-format tries to detect that foo.h is the "main" header for
- // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
- // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
- // _private.cc, _impl.cc etc) in different permutations
- // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
- // better default for Chromium code.
- // - The default for .cc and .mm files is different (r357695) for Google style
- // for the same reason. The plan is to unify this again once the main
- // header detection works for Google's ObjC code, but this hasn't happened
- // yet. Since Chromium has some ObjC code, switching Chromium is blocked
- // on that.
- // - Finally, "If include reordering is harmful, put things in different
- // blocks to prevent it" has been a recommendation for a long time that
- // people are used to. We'll need a dev education push to change this to
- // "If include reordering is harmful, put things in a different block and
- // _prepend that with a comment_ to prevent it" before changing behavior.
- ChromiumStyle.IncludeStyle.IncludeBlocks =
- tooling::IncludeStyle::IBS_Preserve;
-
- if (Language == FormatStyle::LK_Java) {
- ChromiumStyle.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
- ChromiumStyle.ContinuationIndentWidth = 8;
- ChromiumStyle.IndentWidth = 4;
- // See styleguide for import groups:
- // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
- ChromiumStyle.JavaImportGroups = {
- "android",
- "androidx",
- "com",
- "dalvik",
- "junit",
- "org",
- "com.google.android.apps.chrome",
- "org.chromium",
- "java",
- "javax",
- };
- } else if (Language == FormatStyle::LK_JavaScript) {
- ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- ChromiumStyle.AllowShortLoopsOnASingleLine = false;
- } else {
- ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
- ChromiumStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
- ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- ChromiumStyle.AllowShortLoopsOnASingleLine = false;
- ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- ChromiumStyle.DerivePointerAlignment = false;
- if (Language == FormatStyle::LK_ObjC)
- ChromiumStyle.ColumnLimit = 80;
- }
- return ChromiumStyle;
-}
-
-FormatStyle getMozillaStyle() {
- FormatStyle MozillaStyle = getLLVMStyle();
- MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
- MozillaStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
- MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
- FormatStyle::DRTBS_TopLevel;
- MozillaStyle.BinPackArguments = false;
- MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
- MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
- MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
- MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
- MozillaStyle.ConstructorInitializerIndentWidth = 2;
- MozillaStyle.ContinuationIndentWidth = 2;
- MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
- MozillaStyle.FixNamespaceComments = false;
- MozillaStyle.IndentCaseLabels = true;
- MozillaStyle.ObjCSpaceAfterProperty = true;
- MozillaStyle.ObjCSpaceBeforeProtocolList = false;
- MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
- MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
- MozillaStyle.SpaceAfterTemplateKeyword = false;
- return MozillaStyle;
-}
-
-FormatStyle getWebKitStyle() {
- FormatStyle Style = getLLVMStyle();
- Style.AccessModifierOffset = -4;
- Style.AlignAfterOpenBracket = false;
- Style.AlignOperands = FormatStyle::OAS_DontAlign;
- Style.AlignTrailingComments = {};
- Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- Style.ColumnLimit = 0;
- Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
- Style.FixNamespaceComments = false;
- Style.IndentWidth = 4;
- Style.NamespaceIndentation = FormatStyle::NI_Inner;
- Style.ObjCBlockIndentWidth = 4;
- Style.ObjCSpaceAfterProperty = true;
- Style.PointerAlignment = FormatStyle::PAS_Left;
- Style.SpaceBeforeCpp11BracedList = true;
- Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
- return Style;
-}
-
-FormatStyle getGNUStyle() {
- FormatStyle Style = getLLVMStyle();
- Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
- Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- Style.BreakBeforeBraces = FormatStyle::BS_GNU;
- Style.BreakBeforeTernaryOperators = true;
- Style.ColumnLimit = 79;
- Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
- Style.FixNamespaceComments = false;
- Style.KeepFormFeed = true;
- Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
- return Style;
-}
-
-FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
- FormatStyle Style = getLLVMStyle(Language);
- Style.ColumnLimit = 120;
- Style.TabWidth = 4;
- Style.IndentWidth = 4;
- Style.UseTab = FormatStyle::UT_Never;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- Style.BraceWrapping.AfterEnum = true;
- Style.BraceWrapping.AfterFunction = true;
- Style.BraceWrapping.AfterNamespace = true;
- Style.BraceWrapping.AfterObjCDeclaration = true;
- Style.BraceWrapping.AfterStruct = true;
- Style.BraceWrapping.AfterExternBlock = true;
- Style.BraceWrapping.BeforeCatch = true;
- Style.BraceWrapping.BeforeElse = true;
- Style.BraceWrapping.BeforeWhile = false;
- Style.PenaltyReturnTypeOnItsOwnLine = 1000;
- Style.AllowShortEnumsOnASingleLine = false;
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- Style.AllowShortCaseLabelsOnASingleLine = false;
- Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
- Style.AllowShortLoopsOnASingleLine = false;
- Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
- Style.BreakAfterReturnType = FormatStyle::RTBS_None;
- return Style;
-}
-
-FormatStyle getClangFormatStyle() {
- FormatStyle Style = getLLVMStyle();
- Style.InsertBraces = true;
- Style.InsertNewlineAtEOF = true;
- Style.IntegerLiteralSeparator.Decimal = 3;
- Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
- Style.LineEnding = FormatStyle::LE_LF;
- Style.RemoveBracesLLVM = true;
- Style.RemoveEmptyLinesInUnwrappedLines = true;
- Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
- Style.RemoveSemicolon = true;
- return Style;
-}
-
-FormatStyle getNoStyle() {
- FormatStyle NoStyle = getLLVMStyle();
- NoStyle.DisableFormat = true;
- NoStyle.SortIncludes = {};
- NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
- return NoStyle;
-}
-
-bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
- FormatStyle *Style) {
- constexpr StringRef Prefix("inheritparentconfig=");
-
- if (Name.equals_insensitive("llvm"))
- *Style = getLLVMStyle(Language);
- else if (Name.equals_insensitive("chromium"))
- *Style = getChromiumStyle(Language);
- else if (Name.equals_insensitive("mozilla"))
- *Style = getMozillaStyle();
- else if (Name.equals_insensitive("google"))
- *Style = getGoogleStyle(Language);
- else if (Name.equals_insensitive("webkit"))
- *Style = getWebKitStyle();
- else if (Name.equals_insensitive("gnu"))
- *Style = getGNUStyle();
- else if (Name.equals_insensitive("microsoft"))
- *Style = getMicrosoftStyle(Language);
- else if (Name.equals_insensitive("clang-format"))
- *Style = getClangFormatStyle();
- else if (Name.equals_insensitive("none"))
- *Style = getNoStyle();
- else if (Name.equals_insensitive(Prefix.drop_back()))
- Style->InheritConfig = "..";
- else if (Name.size() > Prefix.size() && Name.starts_with_insensitive(Prefix))
- Style->InheritConfig = Name.substr(Prefix.size());
- else
- return false;
-
- Style->Language = Language;
- return true;
-}
-
-ParseError validateQualifierOrder(FormatStyle *Style) {
- // If its empty then it means don't do anything.
- if (Style->QualifierOrder.empty())
- return ParseError::MissingQualifierOrder;
-
- // Ensure the list contains only currently valid qualifiers.
- for (const auto &Qualifier : Style->QualifierOrder) {
- if (Qualifier == "type")
- continue;
- auto token =
- LeftRightQualifierAlignmentFixer::getTokenFromQualifier(Qualifier);
- if (token == tok::identifier)
- return ParseError::InvalidQualifierSpecified;
- }
-
- // Ensure the list is unique (no duplicates).
- std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
- Style->QualifierOrder.end());
- if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
- LLVM_DEBUG(llvm::dbgs()
- << "Duplicate Qualifiers " << Style->QualifierOrder.size()
- << " vs " << UniqueQualifiers.size() << "\n");
- return ParseError::DuplicateQualifierSpecified;
- }
-
- // Ensure the list has 'type' in it.
- if (!llvm::is_contained(Style->QualifierOrder, "type"))
- return ParseError::MissingQualifierType;
-
- return ParseError::Success;
-}
-
-std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
- FormatStyle *Style, bool AllowUnknownOptions,
- llvm::SourceMgr::DiagHandlerTy DiagHandler,
- void *DiagHandlerCtxt, bool IsDotHFile) {
- assert(Style);
- FormatStyle::LanguageKind Language = Style->Language;
- assert(Language != FormatStyle::LK_None);
- if (Config.getBuffer().trim().empty())
- return make_error_code(ParseError::Success);
- Style->StyleSet.Clear();
- std::vector<FormatStyle> Styles;
- llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
- DiagHandlerCtxt);
- // DocumentListTraits<vector<FormatStyle>> uses the context to get default
- // values for the fields, keys for which are missing from the configuration.
- // Mapping also uses the context to get the language to find the correct
- // base style.
- Input.setContext(Style);
- Input.setAllowUnknownKeys(AllowUnknownOptions);
- Input >> Styles;
- if (Input.error())
- return Input.error();
- if (Styles.empty())
- return make_error_code(ParseError::Success);
-
- const auto StyleCount = Styles.size();
-
- // Start from the second style as (only) the first one may be the default.
- for (unsigned I = 1; I < StyleCount; ++I) {
- const auto Lang = Styles[I].Language;
- if (Lang == FormatStyle::LK_None)
- return make_error_code(ParseError::Error);
- // Ensure that each language is configured at most once.
- for (unsigned J = 0; J < I; ++J) {
- if (Lang == Styles[J].Language) {
- LLVM_DEBUG(llvm::dbgs()
- << "Duplicate languages in the config file on positions "
- << J << " and " << I << '\n');
- return make_error_code(ParseError::Error);
- }
- }
- }
-
- int LanguagePos = -1; // Position of the style for Language.
- int CppPos = -1; // Position of the style for C++.
- int CPos = -1; // Position of the style for C.
-
- // Search Styles for Language and store the positions of C++ and C styles in
- // case Language is not found.
- for (unsigned I = 0; I < StyleCount; ++I) {
- const auto Lang = Styles[I].Language;
- if (Lang == Language) {
- LanguagePos = I;
- break;
- }
- if (Lang == FormatStyle::LK_Cpp)
- CppPos = I;
- else if (Lang == FormatStyle::LK_C)
- CPos = I;
- }
-
- // If Language is not found, use the default style if there is one. Otherwise,
- // use the C style for C++ .h files and for backward compatibility, the C++
- // style for .c files.
- if (LanguagePos < 0) {
- if (Styles[0].Language == FormatStyle::LK_None) // Default style.
- LanguagePos = 0;
- else if (IsDotHFile && Language == FormatStyle::LK_Cpp)
- LanguagePos = CPos;
- else if (!IsDotHFile && Language == FormatStyle::LK_C)
- LanguagePos = CppPos;
- if (LanguagePos < 0)
- return make_error_code(ParseError::Unsuitable);
- }
-
- for (const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
- Style->StyleSet.Add(S);
-
- *Style = Styles[LanguagePos];
-
- if (LanguagePos == 0) {
- if (Style->Language == FormatStyle::LK_None) // Default style.
- Style->Language = Language;
- Style->StyleSet.Add(*Style);
- }
-
- if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
- Style->BinPackArguments) {
- // See comment on FormatStyle::TSC_Wrapped.
- return make_error_code(ParseError::BinPackTrailingCommaConflict);
- }
- if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
- return make_error_code(validateQualifierOrder(Style));
- return make_error_code(ParseError::Success);
-}
-
-std::string configurationAsText(const FormatStyle &Style) {
- std::string Text;
- llvm::raw_string_ostream Stream(Text);
- llvm::yaml::Output Output(Stream);
- // We use the same mapping method for input and output, so we need a non-const
- // reference here.
- FormatStyle NonConstStyle = Style;
- expandPresetsBraceWrapping(NonConstStyle);
- expandPresetsSpaceBeforeParens(NonConstStyle);
- expandPresetsSpacesInParens(NonConstStyle);
- Output << NonConstStyle;
-
- return Stream.str();
-}
-
-std::optional<FormatStyle>
-FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
- if (!Styles)
- return std::nullopt;
- auto It = Styles->find(Language);
- if (It == Styles->end())
- return std::nullopt;
- FormatStyle Style = It->second;
- Style.StyleSet = *this;
- return Style;
-}
-
-void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
- assert(Style.Language != LK_None &&
- "Cannot add a style for LK_None to a StyleSet");
- assert(
- !Style.StyleSet.Styles &&
- "Cannot add a style associated with an existing StyleSet to a StyleSet");
- if (!Styles)
- Styles = std::make_shared<MapType>();
- (*Styles)[Style.Language] = std::move(Style);
-}
-
-void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
-
-std::optional<FormatStyle>
-FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
- return StyleSet.Get(Language);
-}
-
-namespace {
-
-void replaceToken(const FormatToken &Token, FormatToken *Next,
- const SourceManager &SourceMgr, tooling::Replacements &Result,
- StringRef Text = "") {
- const auto &Tok = Token.Tok;
- SourceLocation Start;
- if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
- Start = Tok.getLocation();
- Next->WhitespaceRange = Token.WhitespaceRange;
- } else {
- Start = Token.WhitespaceRange.getBegin();
- }
- const auto &Range = CharSourceRange::getCharRange(Start, Tok.getEndLoc());
- cantFail(Result.add(tooling::Replacement(SourceMgr, Range, Text)));
-}
-
-class ParensRemover : public TokenAnalyzer {
-public:
- ParensRemover(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- removeParens(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- const auto &SourceMgr = Env.getSourceManager();
- for (auto *Line : Lines) {
- if (!Line->Children.empty())
- removeParens(Line->Children, Result);
- if (!Line->Affected)
- continue;
- for (const auto *Token = Line->First; Token && !Token->Finalized;
- Token = Token->Next) {
- if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
- replaceToken(*Token, Token->Next, SourceMgr, Result, " ");
- }
- }
- }
-};
-
-class BracesInserter : public TokenAnalyzer {
-public:
- BracesInserter(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- insertBraces(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- const auto &SourceMgr = Env.getSourceManager();
- int OpeningBraceSurplus = 0;
- for (AnnotatedLine *Line : Lines) {
- if (!Line->Children.empty())
- insertBraces(Line->Children, Result);
- if (!Line->Affected && OpeningBraceSurplus == 0)
- continue;
- for (FormatToken *Token = Line->First; Token && !Token->Finalized;
- Token = Token->Next) {
- int BraceCount = Token->BraceCount;
- if (BraceCount == 0)
- continue;
- std::string Brace;
- if (BraceCount < 0) {
- assert(BraceCount == -1);
- if (!Line->Affected)
- break;
- Brace = Token->is(tok::comment) ? "\n{" : "{";
- ++OpeningBraceSurplus;
- } else {
- if (OpeningBraceSurplus == 0)
- break;
- if (OpeningBraceSurplus < BraceCount)
- BraceCount = OpeningBraceSurplus;
- Brace = '\n' + std::string(BraceCount, '}');
- OpeningBraceSurplus -= BraceCount;
- }
- Token->BraceCount = 0;
- const auto Start = Token->Tok.getEndLoc();
- cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
- }
- }
- assert(OpeningBraceSurplus == 0);
- }
-};
-
-class BracesRemover : public TokenAnalyzer {
-public:
- BracesRemover(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- removeBraces(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- const auto &SourceMgr = Env.getSourceManager();
- const auto *End = Lines.end();
- for (const auto *I = Lines.begin(); I != End; ++I) {
- const auto &Line = *I;
- if (!Line->Children.empty())
- removeBraces(Line->Children, Result);
- if (!Line->Affected)
- continue;
- const auto *NextLine = I + 1 == End ? nullptr : I[1];
- for (const auto *Token = Line->First; Token && !Token->Finalized;
- Token = Token->Next) {
- if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
- continue;
- auto *Next = Token->Next;
- assert(Next || Token == Line->Last);
- if (!Next && NextLine)
- Next = NextLine->First;
- replaceToken(*Token, Next, SourceMgr, Result);
- }
- }
- }
-};
-
-class SemiRemover : public TokenAnalyzer {
-public:
- SemiRemover(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- removeSemi(Annotator, AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- void removeSemi(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- auto PrecededByFunctionRBrace = [](const FormatToken &Tok) {
- const auto *Prev = Tok.Previous;
- if (!Prev || Prev->isNot(tok::r_brace))
- return false;
- const auto *LBrace = Prev->MatchingParen;
- return LBrace && LBrace->is(TT_FunctionLBrace);
- };
- const auto &SourceMgr = Env.getSourceManager();
- const auto *End = Lines.end();
- for (const auto *I = Lines.begin(); I != End; ++I) {
- const auto &Line = *I;
- if (!Line->Children.empty())
- removeSemi(Annotator, Line->Children, Result);
- if (!Line->Affected)
- continue;
- Annotator.calculateFormattingInformation(*Line);
- const auto *NextLine = I + 1 == End ? nullptr : I[1];
- for (const auto *Token = Line->First; Token && !Token->Finalized;
- Token = Token->Next) {
- if (Token->isNot(tok::semi) ||
- (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
- continue;
- }
- auto *Next = Token->Next;
- assert(Next || Token == Line->Last);
- if (!Next && NextLine)
- Next = NextLine->First;
- replaceToken(*Token, Next, SourceMgr, Result);
- }
- }
- }
-};
-
-class EnumTrailingCommaEditor : public TokenAnalyzer {
-public:
- EnumTrailingCommaEditor(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- editEnumTrailingComma(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- bool InEnumBraces = false;
- const FormatToken *BeforeRBrace = nullptr;
- const auto &SourceMgr = Env.getSourceManager();
- for (auto *Line : Lines) {
- if (!Line->Children.empty())
- editEnumTrailingComma(Line->Children, Result);
- for (const auto *Token = Line->First; Token && !Token->Finalized;
- Token = Token->Next) {
- if (Token->isNot(TT_EnumRBrace)) {
- if (Token->is(TT_EnumLBrace))
- InEnumBraces = true;
- else if (InEnumBraces && Token->isNot(tok::comment))
- BeforeRBrace = Line->Affected ? Token : nullptr;
- continue;
- }
- InEnumBraces = false;
- if (!BeforeRBrace) // Empty braces or Line not affected.
- continue;
- if (BeforeRBrace->is(tok::comma)) {
- if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
- replaceToken(*BeforeRBrace, BeforeRBrace->Next, SourceMgr, Result);
- } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
- cantFail(Result.add(tooling::Replacement(
- SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0, ",")));
- }
- BeforeRBrace = nullptr;
- }
- }
- }
-};
-
-class JavaScriptRequoter : public TokenAnalyzer {
-public:
- JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- requoteJSStringLiteral(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- // Replaces double/single-quoted string literal as appropriate, re-escaping
- // the contents in the process.
- void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- for (AnnotatedLine *Line : Lines) {
- requoteJSStringLiteral(Line->Children, Result);
- if (!Line->Affected)
- continue;
- for (FormatToken *FormatTok = Line->First; FormatTok;
- FormatTok = FormatTok->Next) {
- StringRef Input = FormatTok->TokenText;
- if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
- // NB: testing for not starting with a double quote to avoid
- // breaking `template strings`.
- (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
- !Input.starts_with("\"")) ||
- (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
- !Input.starts_with("\'"))) {
- continue;
- }
-
- // Change start and end quote.
- bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
- SourceLocation Start = FormatTok->Tok.getLocation();
- auto Replace = [&](SourceLocation Start, unsigned Length,
- StringRef ReplacementText) {
- auto Err = Result.add(tooling::Replacement(
- Env.getSourceManager(), Start, Length, ReplacementText));
- // FIXME: handle error. For now, print error message and skip the
- // replacement for release version.
- if (Err) {
- llvm::errs() << toString(std::move(Err)) << "\n";
- assert(false);
- }
- };
- Replace(Start, 1, IsSingle ? "'" : "\"");
- Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
- IsSingle ? "'" : "\"");
-
- // Escape internal quotes.
- bool Escaped = false;
- for (size_t i = 1; i < Input.size() - 1; i++) {
- switch (Input[i]) {
- case '\\':
- if (!Escaped && i + 1 < Input.size() &&
- ((IsSingle && Input[i + 1] == '"') ||
- (!IsSingle && Input[i + 1] == '\''))) {
- // Remove this \, it's escaping a " or ' that no longer needs
- // escaping
- Replace(Start.getLocWithOffset(i), 1, "");
- continue;
- }
- Escaped = !Escaped;
- break;
- case '\"':
- case '\'':
- if (!Escaped && IsSingle == (Input[i] == '\'')) {
- // Escape the quote.
- Replace(Start.getLocWithOffset(i), 0, "\\");
- }
- Escaped = false;
- break;
- default:
- Escaped = false;
- break;
- }
- }
- }
- }
- }
-};
-
-class Formatter : public TokenAnalyzer {
-public:
- Formatter(const Environment &Env, const FormatStyle &Style,
- FormattingAttemptStatus *Status)
- : TokenAnalyzer(Env, Style), Status(Status) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- tooling::Replacements Result;
- deriveLocalStyle(AnnotatedLines);
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- for (AnnotatedLine *Line : AnnotatedLines)
- Annotator.calculateFormattingInformation(*Line);
- Annotator.setCommentLineLevels(AnnotatedLines);
-
- WhitespaceManager Whitespaces(
- Env.getSourceManager(), Style,
- Style.LineEnding > FormatStyle::LE_CRLF
- ? WhitespaceManager::inputUsesCRLF(
- Env.getSourceManager().getBufferData(Env.getFileID()),
- Style.LineEnding == FormatStyle::LE_DeriveCRLF)
- : Style.LineEnding == FormatStyle::LE_CRLF);
- ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
- Env.getSourceManager(), Whitespaces, Encoding,
- BinPackInconclusiveFunctions);
- unsigned Penalty =
- UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
- Tokens.getKeywords(), Env.getSourceManager(),
- Status)
- .format(AnnotatedLines, /*DryRun=*/false,
- /*AdditionalIndent=*/0,
- /*FixBadIndentation=*/false,
- /*FirstStartColumn=*/Env.getFirstStartColumn(),
- /*NextStartColumn=*/Env.getNextStartColumn(),
- /*LastStartColumn=*/Env.getLastStartColumn());
- for (const auto &R : Whitespaces.generateReplacements())
- if (Result.add(R))
- return std::make_pair(Result, 0);
- return std::make_pair(Result, Penalty);
- }
-
-private:
- bool
- hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
- for (const AnnotatedLine *Line : Lines) {
- if (hasCpp03IncompatibleFormat(Line->Children))
- return true;
- for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
- if (!Tok->hasWhitespaceBefore()) {
- if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
- return true;
- if (Tok->is(TT_TemplateCloser) &&
- Tok->Previous->is(TT_TemplateCloser)) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
- int AlignmentDiff = 0;
-
- for (const AnnotatedLine *Line : Lines) {
- AlignmentDiff += countVariableAlignments(Line->Children);
-
- for (const auto *Tok = Line->getFirstNonComment(); Tok; Tok = Tok->Next) {
- if (Tok->isNot(TT_PointerOrReference))
- continue;
-
- const auto *Prev = Tok->Previous;
- const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
- const bool SpaceBefore = Tok->hasWhitespaceBefore();
-
- // e.g. `int **`, `int*&`, etc.
- while (Tok->Next && Tok->Next->is(TT_PointerOrReference))
- Tok = Tok->Next;
-
- const auto *Next = Tok->Next;
- const bool FollowedByName = Next && Next->Tok.getIdentifierInfo();
- const bool SpaceAfter = Next && Next->hasWhitespaceBefore();
-
- if ((!PrecededByName && !FollowedByName) ||
- // e.g. `int * i` or `int*i`
- (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
- continue;
- }
-
- if ((PrecededByName && SpaceBefore) ||
- (FollowedByName && !SpaceAfter)) {
- // Right alignment.
- ++AlignmentDiff;
- } else if ((PrecededByName && !SpaceBefore) ||
- (FollowedByName && SpaceAfter)) {
- // Left alignment.
- --AlignmentDiff;
- }
- }
- }
-
- return AlignmentDiff;
- }
-
- void
- deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
- bool HasBinPackedFunction = false;
- bool HasOnePerLineFunction = false;
- for (AnnotatedLine *Line : AnnotatedLines) {
- if (!Line->First->Next)
- continue;
- FormatToken *Tok = Line->First->Next;
- while (Tok->Next) {
- if (Tok->is(PPK_BinPacked))
- HasBinPackedFunction = true;
- if (Tok->is(PPK_OnePerLine))
- HasOnePerLineFunction = true;
-
- Tok = Tok->Next;
- }
- }
- if (Style.DerivePointerAlignment) {
- const auto NetRightCount = countVariableAlignments(AnnotatedLines);
- if (NetRightCount > 0)
- Style.PointerAlignment = FormatStyle::PAS_Right;
- else if (NetRightCount < 0)
- Style.PointerAlignment = FormatStyle::PAS_Left;
- Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
- }
- if (Style.Standard == FormatStyle::LS_Auto) {
- Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
- ? FormatStyle::LS_Latest
- : FormatStyle::LS_Cpp03;
- }
- BinPackInconclusiveFunctions =
- HasBinPackedFunction || !HasOnePerLineFunction;
- }
-
- bool BinPackInconclusiveFunctions;
- FormattingAttemptStatus *Status;
-};
-
-/// TrailingCommaInserter inserts trailing commas into container literals.
-/// E.g.:
-/// const x = [
-/// 1,
-/// ];
-/// TrailingCommaInserter runs after formatting. To avoid causing a required
-/// reformatting (and thus reflow), it never inserts a comma that'd exceed the
-/// ColumnLimit.
-///
-/// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
-/// is conceptually incompatible with bin packing.
-class TrailingCommaInserter : public TokenAnalyzer {
-public:
- TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
- tooling::Replacements Result;
- insertTrailingCommas(AnnotatedLines, Result);
- return {Result, 0};
- }
-
-private:
- /// Inserts trailing commas in [] and {} initializers if they wrap over
- /// multiple lines.
- void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
- tooling::Replacements &Result) {
- for (AnnotatedLine *Line : Lines) {
- insertTrailingCommas(Line->Children, Result);
- if (!Line->Affected)
- continue;
- for (FormatToken *FormatTok = Line->First; FormatTok;
- FormatTok = FormatTok->Next) {
- if (FormatTok->NewlinesBefore == 0)
- continue;
- FormatToken *Matching = FormatTok->MatchingParen;
- if (!Matching || !FormatTok->getPreviousNonComment())
- continue;
- if (!(FormatTok->is(tok::r_square) &&
- Matching->is(TT_ArrayInitializerLSquare)) &&
- !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
- continue;
- }
- FormatToken *Prev = FormatTok->getPreviousNonComment();
- if (Prev->is(tok::comma) || Prev->is(tok::semi))
- continue;
- // getEndLoc is not reliably set during re-lexing, use text length
- // instead.
- SourceLocation Start =
- Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
- // If inserting a comma would push the code over the column limit, skip
- // this location - it'd introduce an unstable formatting due to the
- // required reflow.
- unsigned ColumnNumber =
- Env.getSourceManager().getSpellingColumnNumber(Start);
- if (ColumnNumber > Style.ColumnLimit)
- continue;
- // Comma insertions cannot conflict with each other, and this pass has a
- // clean set of Replacements, so the operation below cannot fail.
- cantFail(Result.add(
- tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
- }
- }
- }
-};
-
-// This class clean up the erroneous/redundant code around the given ranges in
-// file.
-class Cleaner : public TokenAnalyzer {
-public:
- Cleaner(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style),
- DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
-
- // FIXME: eliminate unused parameters.
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- // FIXME: in the current implementation the granularity of affected range
- // is an annotated line. However, this is not sufficient. Furthermore,
- // redundant code introduced by replacements does not necessarily
- // intercept with ranges of replacements that result in the redundancy.
- // To determine if some redundant code is actually introduced by
- // replacements(e.g. deletions), we need to come up with a more
- // sophisticated way of computing affected ranges.
- AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
-
- checkEmptyNamespace(AnnotatedLines);
-
- for (auto *Line : AnnotatedLines)
- cleanupLine(Line);
-
- return {generateFixes(), 0};
- }
-
-private:
- void cleanupLine(AnnotatedLine *Line) {
- for (auto *Child : Line->Children)
- cleanupLine(Child);
-
- if (Line->Affected) {
- cleanupRight(Line->First, tok::comma, tok::comma);
- cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
- cleanupRight(Line->First, tok::l_paren, tok::comma);
- cleanupLeft(Line->First, tok::comma, tok::r_paren);
- cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
- cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
- cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
- }
- }
-
- bool containsOnlyComments(const AnnotatedLine &Line) {
- for (FormatToken *Tok = Line.First; Tok; Tok = Tok->Next)
- if (Tok->isNot(tok::comment))
- return false;
- return true;
- }
-
- // Iterate through all lines and remove any empty (nested) namespaces.
- void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
- std::set<unsigned> DeletedLines;
- for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
- auto &Line = *AnnotatedLines[i];
- if (Line.startsWithNamespace())
- checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
- }
-
- for (auto Line : DeletedLines) {
- FormatToken *Tok = AnnotatedLines[Line]->First;
- while (Tok) {
- deleteToken(Tok);
- Tok = Tok->Next;
- }
- }
- }
-
- // The function checks if the namespace, which starts from \p CurrentLine, and
- // its nested namespaces are empty and delete them if they are empty. It also
- // sets \p NewLine to the last line checked.
- // Returns true if the current namespace is empty.
- bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- unsigned CurrentLine, unsigned &NewLine,
- std::set<unsigned> &DeletedLines) {
- unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
- if (Style.BraceWrapping.AfterNamespace) {
- // If the left brace is in a new line, we should consume it first so that
- // it does not make the namespace non-empty.
- // FIXME: error handling if there is no left brace.
- if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
- NewLine = CurrentLine;
- return false;
- }
- } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
- return false;
- }
- while (++CurrentLine < End) {
- if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
- break;
-
- if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
- if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
- DeletedLines)) {
- return false;
- }
- CurrentLine = NewLine;
- continue;
- }
-
- if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
- continue;
-
- // If there is anything other than comments or nested namespaces in the
- // current namespace, the namespace cannot be empty.
- NewLine = CurrentLine;
- return false;
- }
-
- NewLine = CurrentLine;
- if (CurrentLine >= End)
- return false;
-
- // Check if the empty namespace is actually affected by changed ranges.
- if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
- AnnotatedLines[InitLine]->First->Tok.getLocation(),
- AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
- return false;
- }
-
- for (unsigned i = InitLine; i <= CurrentLine; ++i)
- DeletedLines.insert(i);
-
- return true;
- }
-
- // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
- // of the token in the pair if the left token has \p LK token kind and the
- // right token has \p RK token kind. If \p DeleteLeft is true, the left token
- // is deleted on match; otherwise, the right token is deleted.
- template <typename LeftKind, typename RightKind>
- void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
- bool DeleteLeft) {
- auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
- for (auto *Res = Tok.Next; Res; Res = Res->Next) {
- if (Res->isNot(tok::comment) &&
- DeletedTokens.find(Res) == DeletedTokens.end()) {
- return Res;
- }
- }
- return nullptr;
- };
- for (auto *Left = Start; Left;) {
- auto *Right = NextNotDeleted(*Left);
- if (!Right)
- break;
- if (Left->is(LK) && Right->is(RK)) {
- deleteToken(DeleteLeft ? Left : Right);
- for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
- deleteToken(Tok);
- // If the right token is deleted, we should keep the left token
- // unchanged and pair it with the new right token.
- if (!DeleteLeft)
- continue;
- }
- Left = Right;
- }
- }
-
- template <typename LeftKind, typename RightKind>
- void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
- cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
- }
-
- template <typename LeftKind, typename RightKind>
- void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
- cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
- }
-
- // Delete the given token.
- inline void deleteToken(FormatToken *Tok) {
- if (Tok)
- DeletedTokens.insert(Tok);
- }
-
- tooling::Replacements generateFixes() {
- tooling::Replacements Fixes;
- SmallVector<FormatToken *> Tokens;
- std::copy(DeletedTokens.begin(), DeletedTokens.end(),
- std::back_inserter(Tokens));
-
- // Merge multiple continuous token deletions into one big deletion so that
- // the number of replacements can be reduced. This makes computing affected
- // ranges more efficient when we run reformat on the changed code.
- unsigned Idx = 0;
- while (Idx < Tokens.size()) {
- unsigned St = Idx, End = Idx;
- while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
- ++End;
- auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
- Tokens[End]->Tok.getEndLoc());
- auto Err =
- Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
- // FIXME: better error handling. for now just print error message and skip
- // for the release version.
- if (Err) {
- llvm::errs() << toString(std::move(Err)) << "\n";
- assert(false && "Fixes must not conflict!");
- }
- Idx = End + 1;
- }
-
- return Fixes;
- }
-
- // Class for less-than inequality comparason for the set `RedundantTokens`.
- // We store tokens in the order they appear in the translation unit so that
- // we do not need to sort them in `generateFixes()`.
- struct FormatTokenLess {
- FormatTokenLess(const SourceManager &SM) : SM(SM) {}
-
- bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
- return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
- RHS->Tok.getLocation());
- }
- const SourceManager &SM;
- };
-
- // Tokens to be deleted.
- std::set<FormatToken *, FormatTokenLess> DeletedTokens;
-};
-
-class ObjCHeaderStyleGuesser : public TokenAnalyzer {
-public:
- ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
- : TokenAnalyzer(Env, Style), IsObjC(false) {}
-
- std::pair<tooling::Replacements, unsigned>
- analyze(TokenAnnotator &Annotator,
- SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- FormatTokenLexer &Tokens) override {
- assert(Style.Language == FormatStyle::LK_Cpp);
- IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
- Tokens.getKeywords());
- tooling::Replacements Result;
- return {Result, 0};
- }
-
- bool isObjC() { return IsObjC; }
-
-private:
- static bool
- guessIsObjC(const SourceManager &SourceManager,
- const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
- const AdditionalKeywords &Keywords) {
- // Keep this array sorted, since we are binary searching over it.
- static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
- "CGFloat",
- "CGPoint",
- "CGPointMake",
- "CGPointZero",
- "CGRect",
- "CGRectEdge",
- "CGRectInfinite",
- "CGRectMake",
- "CGRectNull",
- "CGRectZero",
- "CGSize",
- "CGSizeMake",
- "CGVector",
- "CGVectorMake",
- "FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
- "FOUNDATION_EXTERN",
- "NSAffineTransform",
- "NSArray",
- "NSAttributedString",
- "NSBlockOperation",
- "NSBundle",
- "NSCache",
- "NSCalendar",
- "NSCharacterSet",
- "NSCountedSet",
- "NSData",
- "NSDataDetector",
- "NSDecimal",
- "NSDecimalNumber",
- "NSDictionary",
- "NSEdgeInsets",
- "NSError",
- "NSErrorDomain",
- "NSHashTable",
- "NSIndexPath",
- "NSIndexSet",
- "NSInteger",
- "NSInvocationOperation",
- "NSLocale",
- "NSMapTable",
- "NSMutableArray",
- "NSMutableAttributedString",
- "NSMutableCharacterSet",
- "NSMutableData",
- "NSMutableDictionary",
- "NSMutableIndexSet",
- "NSMutableOrderedSet",
- "NSMutableSet",
- "NSMutableString",
- "NSNumber",
- "NSNumberFormatter",
- "NSObject",
- "NSOperation",
- "NSOperationQueue",
- "NSOperationQueuePriority",
- "NSOrderedSet",
- "NSPoint",
- "NSPointerArray",
- "NSQualityOfService",
- "NSRange",
- "NSRect",
- "NSRegularExpression",
- "NSSet",
- "NSSize",
- "NSString",
- "NSTimeZone",
- "NSUInteger",
- "NSURL",
- "NSURLComponents",
- "NSURLQueryItem",
- "NSUUID",
- "NSValue",
- "NS_ASSUME_NONNULL_BEGIN",
- "UIImage",
- "UIView",
- };
- assert(llvm::is_sorted(FoundationIdentifiers));
-
- for (auto *Line : AnnotatedLines) {
- if (Line->First && (Line->First->TokenText.starts_with("#") ||
- Line->First->TokenText == "__pragma" ||
- Line->First->TokenText == "_Pragma")) {
- continue;
- }
- for (const FormatToken *FormatTok = Line->First; FormatTok;
- FormatTok = FormatTok->Next) {
- if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
- (FormatTok->isNot(tok::objc_not_keyword) ||
- FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
- tok::l_brace))) ||
- (FormatTok->Tok.isAnyIdentifier() &&
- llvm::binary_search(FoundationIdentifiers,
- FormatTok->TokenText)) ||
- FormatTok->is(TT_ObjCStringLiteral) ||
- FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
- Keywords.kw_NS_ERROR_ENUM,
- Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
- TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
- TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
- TT_ObjCProperty, TT_ObjCSelector)) {
- LLVM_DEBUG(llvm::dbgs()
- << "Detected ObjC at location "
- << FormatTok->Tok.getLocation().printToString(
- SourceManager)
- << " token: " << FormatTok->TokenText << " token type: "
- << getTokenTypeName(FormatTok->getType()) << "\n");
- return true;
- }
- }
- if (guessIsObjC(SourceManager, Line->Children, Keywords))
- return true;
- }
- return false;
- }
-
- bool IsObjC;
-};
-
-struct IncludeDirective {
- StringRef Filename;
- StringRef Text;
- unsigned Offset;
- int Category;
- int Priority;
-};
-
-struct JavaImportDirective {
- StringRef Identifier;
- StringRef Text;
- unsigned Offset;
- SmallVector<StringRef> AssociatedCommentLines;
- bool IsStatic;
-};
-
-} // end anonymous namespace
-
-// Determines whether 'Ranges' intersects with ('Start', 'End').
-static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
- unsigned End) {
- for (const auto &Range : Ranges) {
- if (Range.getOffset() < End &&
- Range.getOffset() + Range.getLength() > Start) {
- return true;
- }
- }
- return false;
-}
-
-// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
-// before sorting/deduplicating. Index is the index of the include under the
-// cursor in the original set of includes. If this include has duplicates, it is
-// the index of the first of the duplicates as the others are going to be
-// removed. OffsetToEOL describes the cursor's position relative to the end of
-// its current line.
-// If `Cursor` is not on any #include, `Index` will be
-// std::numeric_limits<unsigned>::max().
-static std::pair<unsigned, unsigned>
-FindCursorIndex(const ArrayRef<IncludeDirective> &Includes,
- const ArrayRef<unsigned> &Indices, unsigned Cursor) {
- unsigned CursorIndex = std::numeric_limits<unsigned>::max();
- unsigned OffsetToEOL = 0;
- for (int i = 0, e = Includes.size(); i != e; ++i) {
- unsigned Start = Includes[Indices[i]].Offset;
- unsigned End = Start + Includes[Indices[i]].Text.size();
- if (!(Cursor >= Start && Cursor < End))
- continue;
- CursorIndex = Indices[i];
- OffsetToEOL = End - Cursor;
- // Put the cursor on the only remaining #include among the duplicate
- // #includes.
- while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
- CursorIndex = i;
- break;
- }
- return std::make_pair(CursorIndex, OffsetToEOL);
-}
-
-// Replace all "\r\n" with "\n".
-std::string replaceCRLF(const std::string &Code) {
- std::string NewCode;
- size_t Pos = 0, LastPos = 0;
-
- do {
- Pos = Code.find("\r\n", LastPos);
- if (Pos == LastPos) {
- ++LastPos;
- continue;
- }
- if (Pos == std::string::npos) {
- NewCode += Code.substr(LastPos);
- break;
- }
- NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
- LastPos = Pos + 2;
- } while (Pos != std::string::npos);
-
- return NewCode;
-}
-
-// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
-// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
-// source order.
-// #include directives with the same text will be deduplicated, and only the
-// first #include in the duplicate #includes remains. If the `Cursor` is
-// provided and put on a deleted #include, it will be moved to the remaining
-// #include in the duplicate #includes.
-static void sortCppIncludes(const FormatStyle &Style,
- const ArrayRef<IncludeDirective> &Includes,
- ArrayRef<tooling::Range> Ranges, StringRef FileName,
- StringRef Code, tooling::Replacements &Replaces,
- unsigned *Cursor) {
- tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
- const unsigned IncludesBeginOffset = Includes.front().Offset;
- const unsigned IncludesEndOffset =
- Includes.back().Offset + Includes.back().Text.size();
- const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
- if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
- return;
- SmallVector<unsigned, 16> Indices =
- llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
-
- if (Style.SortIncludes.Enabled) {
- stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
- SmallString<128> LHSStem, RHSStem;
- if (Style.SortIncludes.IgnoreExtension) {
- LHSStem = Includes[LHSI].Filename;
- RHSStem = Includes[RHSI].Filename;
- llvm::sys::path::replace_extension(LHSStem, "");
- llvm::sys::path::replace_extension(RHSStem, "");
- }
- std::string LHSStemLower, RHSStemLower;
- std::string LHSFilenameLower, RHSFilenameLower;
- if (Style.SortIncludes.IgnoreCase) {
- LHSStemLower = LHSStem.str().lower();
- RHSStemLower = RHSStem.str().lower();
- LHSFilenameLower = Includes[LHSI].Filename.lower();
- RHSFilenameLower = Includes[RHSI].Filename.lower();
- }
- return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
- LHSFilenameLower, Includes[LHSI].Filename) <
- std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
- RHSFilenameLower, Includes[RHSI].Filename);
- });
- }
-
- // The index of the include on which the cursor will be put after
- // sorting/deduplicating.
- unsigned CursorIndex;
- // The offset from cursor to the end of line.
- unsigned CursorToEOLOffset;
- if (Cursor) {
- std::tie(CursorIndex, CursorToEOLOffset) =
- FindCursorIndex(Includes, Indices, *Cursor);
- }
-
- // Deduplicate #includes.
- Indices.erase(llvm::unique(Indices,
- [&](unsigned LHSI, unsigned RHSI) {
- return Includes[LHSI].Text.trim() ==
- Includes[RHSI].Text.trim();
- }),
- Indices.end());
-
- int CurrentCategory = Includes.front().Category;
-
- // If the #includes are out of order, we generate a single replacement fixing
- // the entire block. Otherwise, no replacement is generated.
- // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
- // enough as additional newlines might be added or removed across #include
- // blocks. This we handle below by generating the updated #include blocks and
- // comparing it to the original.
- if (Indices.size() == Includes.size() && is_sorted(Indices) &&
- Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) {
- return;
- }
-
- const auto OldCursor = Cursor ? *Cursor : 0;
- std::string result;
- for (unsigned Index : Indices) {
- if (!result.empty()) {
- result += "\n";
- if (Style.IncludeStyle.IncludeBlocks ==
- tooling::IncludeStyle::IBS_Regroup &&
- CurrentCategory != Includes[Index].Category) {
- result += "\n";
- }
- }
- result += Includes[Index].Text;
- if (Cursor && CursorIndex == Index)
- *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
- CurrentCategory = Includes[Index].Category;
- }
-
- if (Cursor && *Cursor >= IncludesEndOffset)
- *Cursor += result.size() - IncludesBlockSize;
-
- // If the #includes are out of order, we generate a single replacement fixing
- // the entire range of blocks. Otherwise, no replacement is generated.
- if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
- IncludesBeginOffset, IncludesBlockSize)))) {
- if (Cursor)
- *Cursor = OldCursor;
- return;
- }
-
- auto Err = Replaces.add(tooling::Replacement(
- FileName, Includes.front().Offset, IncludesBlockSize, result));
- // FIXME: better error handling. For now, just skip the replacement for the
- // release version.
- if (Err) {
- llvm::errs() << toString(std::move(Err)) << "\n";
- assert(false);
- }
-}
-
-tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName,
- tooling::Replacements &Replaces,
- unsigned *Cursor) {
- unsigned Prev = llvm::StringSwitch<size_t>(Code)
- .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
- .Default(0);
- unsigned SearchFrom = 0;
- SmallVector<StringRef, 4> Matches;
- SmallVector<IncludeDirective, 16> IncludesInBlock;
-
- // In compiled files, consider the first #include to be the main #include of
- // the file if it is not a system #include. This ensures that the header
- // doesn't have hidden dependencies
- // (http://llvm.org/docs/CodingStandards.html#include-style).
- //
- // FIXME: Do some validation, e.g. edit distance of the base name, to fix
- // cases where the first #include is unlikely to be the main header.
- tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
- bool FirstIncludeBlock = true;
- bool MainIncludeFound = false;
- bool FormattingOff = false;
-
- // '[' must be the first and '-' the last character inside [...].
- llvm::Regex RawStringRegex(
- "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
- SmallVector<StringRef, 2> RawStringMatches;
- std::string RawStringTermination = ")\"";
-
- for (const auto Size = Code.size(); SearchFrom < Size;) {
- size_t Pos = SearchFrom;
- if (Code[SearchFrom] != '\n') {
- do { // Search for the first newline while skipping line splices.
- ++Pos;
- Pos = Code.find('\n', Pos);
- } while (Pos != StringRef::npos && Code[Pos - 1] == '\\');
- }
-
- StringRef Line =
- Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
-
- StringRef Trimmed = Line.trim();
-
- // #includes inside raw string literals need to be ignored.
- // or we will sort the contents of the string.
- // Skip past until we think we are at the rawstring literal close.
- if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
- std::string CharSequence = RawStringMatches[1].str();
- RawStringTermination = ")" + CharSequence + "\"";
- FormattingOff = true;
- }
-
- if (Trimmed.contains(RawStringTermination))
- FormattingOff = false;
-
- bool IsBlockComment = false;
-
- if (isClangFormatOff(Trimmed)) {
- FormattingOff = true;
- } else if (isClangFormatOn(Trimmed)) {
- FormattingOff = false;
- } else if (Trimmed.starts_with("/*")) {
- IsBlockComment = true;
- Pos = Code.find("*/", SearchFrom + 2);
- }
-
- const bool EmptyLineSkipped =
- Trimmed.empty() &&
- (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
- Style.IncludeStyle.IncludeBlocks ==
- tooling::IncludeStyle::IBS_Regroup);
-
- bool MergeWithNextLine = Trimmed.ends_with("\\");
- if (!FormattingOff && !MergeWithNextLine) {
- if (!IsBlockComment &&
- tooling::HeaderIncludes::IncludeRegex.match(Trimmed, &Matches)) {
- StringRef IncludeName = Matches[2];
- if (Trimmed.contains("/*") && !Trimmed.contains("*/")) {
- // #include with a start of a block comment, but without the end.
- // Need to keep all the lines until the end of the comment together.
- // FIXME: This is somehow simplified check that probably does not work
- // correctly if there are multiple comments on a line.
- Pos = Code.find("*/", SearchFrom);
- Line = Code.substr(
- Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
- }
- int Category = Categories.getIncludePriority(
- IncludeName,
- /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
- int Priority = Categories.getSortIncludePriority(
- IncludeName, !MainIncludeFound && FirstIncludeBlock);
- if (Category == 0)
- MainIncludeFound = true;
- IncludesInBlock.push_back(
- {IncludeName, Line, Prev, Category, Priority});
- } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
- sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
- Replaces, Cursor);
- IncludesInBlock.clear();
- if (Trimmed.starts_with("#pragma hdrstop")) // Precompiled headers.
- FirstIncludeBlock = true;
- else
- FirstIncludeBlock = false;
- }
- }
- if (Pos == StringRef::npos || Pos + 1 == Code.size())
- break;
-
- if (!MergeWithNextLine)
- Prev = Pos + 1;
- SearchFrom = Pos + 1;
- }
- if (!IncludesInBlock.empty()) {
- sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
- Cursor);
- }
- return Replaces;
-}
-
-// Returns group number to use as a first order sort on imports. Gives
-// std::numeric_limits<unsigned>::max() if the import does not match any given
-// groups.
-static unsigned findJavaImportGroup(const FormatStyle &Style,
- StringRef ImportIdentifier) {
- unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
- unsigned LongestMatchLength = 0;
- for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
- const std::string &GroupPrefix = Style.JavaImportGroups[I];
- if (ImportIdentifier.starts_with(GroupPrefix) &&
- GroupPrefix.length() > LongestMatchLength) {
- LongestMatchIndex = I;
- LongestMatchLength = GroupPrefix.length();
- }
- }
- return LongestMatchIndex;
-}
-
-// Sorts and deduplicates a block of includes given by 'Imports' based on
-// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
-// Import declarations with the same text will be deduplicated. Between each
-// import group, a newline is inserted, and within each import group, a
-// lexicographic sort based on ASCII value is performed.
-static void sortJavaImports(const FormatStyle &Style,
- const ArrayRef<JavaImportDirective> &Imports,
- ArrayRef<tooling::Range> Ranges, StringRef FileName,
- StringRef Code, tooling::Replacements &Replaces) {
- unsigned ImportsBeginOffset = Imports.front().Offset;
- unsigned ImportsEndOffset =
- Imports.back().Offset + Imports.back().Text.size();
- unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
- if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
- return;
-
- SmallVector<unsigned, 16> Indices =
- llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
- SmallVector<unsigned, 16> JavaImportGroups;
- JavaImportGroups.reserve(Imports.size());
- for (const JavaImportDirective &Import : Imports)
- JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
-
- bool StaticImportAfterNormalImport =
- Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
- sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
- // Negating IsStatic to push static imports above non-static imports.
- return std::make_tuple(!Imports[LHSI].IsStatic ^
- StaticImportAfterNormalImport,
- JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
- std::make_tuple(!Imports[RHSI].IsStatic ^
- StaticImportAfterNormalImport,
- JavaImportGroups[RHSI], Imports[RHSI].Identifier);
- });
-
- // Deduplicate imports.
- Indices.erase(llvm::unique(Indices,
- [&](unsigned LHSI, unsigned RHSI) {
- return Imports[LHSI].Text == Imports[RHSI].Text;
- }),
- Indices.end());
-
- bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
- unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
-
- std::string result;
- for (unsigned Index : Indices) {
- if (!result.empty()) {
- result += "\n";
- if (CurrentIsStatic != Imports[Index].IsStatic ||
- CurrentImportGroup != JavaImportGroups[Index]) {
- result += "\n";
- }
- }
- for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
- result += CommentLine;
- result += "\n";
- }
- result += Imports[Index].Text;
- CurrentIsStatic = Imports[Index].IsStatic;
- CurrentImportGroup = JavaImportGroups[Index];
- }
-
- // If the imports are out of order, we generate a single replacement fixing
- // the entire block. Otherwise, no replacement is generated.
- if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
- Imports.front().Offset, ImportsBlockSize)))) {
- return;
- }
-
- auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
- ImportsBlockSize, result));
- // FIXME: better error handling. For now, just skip the replacement for the
- // release version.
- if (Err) {
- llvm::errs() << toString(std::move(Err)) << "\n";
- assert(false);
- }
-}
-
-namespace {
-
-constexpr StringRef
- JavaImportRegexPattern("^import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;");
-
-constexpr StringRef JavaPackageRegexPattern("^package[\t ]");
-
-} // anonymous namespace
-
-tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName,
- tooling::Replacements &Replaces) {
- unsigned Prev = 0;
- bool HasImport = false;
- llvm::Regex ImportRegex(JavaImportRegexPattern);
- llvm::Regex PackageRegex(JavaPackageRegexPattern);
- SmallVector<StringRef, 4> Matches;
- SmallVector<JavaImportDirective, 16> ImportsInBlock;
- SmallVector<StringRef> AssociatedCommentLines;
-
- for (bool FormattingOff = false;;) {
- auto Pos = Code.find('\n', Prev);
- auto GetLine = [&] {
- return Code.substr(Prev,
- (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
- };
- StringRef Line = GetLine();
-
- StringRef Trimmed = Line.trim();
- if (Trimmed.empty() || PackageRegex.match(Trimmed)) {
- // Skip empty line and package statement.
- } else if (isClangFormatOff(Trimmed)) {
- FormattingOff = true;
- } else if (isClangFormatOn(Trimmed)) {
- FormattingOff = false;
- } else if (Trimmed.starts_with("//")) {
- // Associating comments within the imports with the nearest import below.
- if (HasImport)
- AssociatedCommentLines.push_back(Line);
- } else if (Trimmed.starts_with("/*")) {
- Pos = Code.find("*/", Pos + 2);
- if (Pos != StringRef::npos)
- Pos = Code.find('\n', Pos + 2);
- if (HasImport) {
- // Extend `Line` for a multiline comment to include all lines the
- // comment spans.
- Line = GetLine();
- AssociatedCommentLines.push_back(Line);
- }
- } else if (ImportRegex.match(Trimmed, &Matches)) {
- if (FormattingOff) {
- // If at least one import line has formatting turned off, turn off
- // formatting entirely.
- return Replaces;
- }
- StringRef Static = Matches[1];
- StringRef Identifier = Matches[2];
- bool IsStatic = false;
- if (Static.contains("static"))
- IsStatic = true;
- ImportsInBlock.push_back(
- {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
- HasImport = true;
- AssociatedCommentLines.clear();
- } else {
- // `Trimmed` is neither empty, nor a comment or a package/import
- // statement.
- break;
- }
- if (Pos == StringRef::npos || Pos + 1 == Code.size())
- break;
- Prev = Pos + 1;
- }
- if (HasImport)
- sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
- return Replaces;
-}
-
-bool isMpegTS(StringRef Code) {
- // MPEG transport streams use the ".ts" file extension. clang-format should
- // not attempt to format those. MPEG TS' frame format starts with 0x47 every
- // 189 bytes - detect that and return.
- return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
-}
-
-bool isLikelyXml(StringRef Code) { return Code.ltrim().starts_with("<"); }
-
-tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName, unsigned *Cursor) {
- tooling::Replacements Replaces;
- if (!Style.SortIncludes.Enabled || Style.DisableFormat)
- return Replaces;
- if (isLikelyXml(Code))
- return Replaces;
- if (Style.isJavaScript()) {
- if (isMpegTS(Code))
- return Replaces;
- return sortJavaScriptImports(Style, Code, Ranges, FileName);
- }
- if (Style.isJava())
- return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
- if (Style.isCpp())
- sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
- return Replaces;
-}
-
-template <typename T>
-static Expected<tooling::Replacements>
-processReplacements(T ProcessFunc, StringRef Code,
- const tooling::Replacements &Replaces,
- const FormatStyle &Style) {
- if (Replaces.empty())
- return tooling::Replacements();
-
- auto NewCode = applyAllReplacements(Code, Replaces);
- if (!NewCode)
- return NewCode.takeError();
- std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
- StringRef FileName = Replaces.begin()->getFilePath();
-
- tooling::Replacements FormatReplaces =
- ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
-
- return Replaces.merge(FormatReplaces);
-}
-
-Expected<tooling::Replacements>
-formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
- const FormatStyle &Style) {
- // We need to use lambda function here since there are two versions of
- // `sortIncludes`.
- auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
- std::vector<tooling::Range> Ranges,
- StringRef FileName) -> tooling::Replacements {
- return sortIncludes(Style, Code, Ranges, FileName);
- };
- auto SortedReplaces =
- processReplacements(SortIncludes, Code, Replaces, Style);
- if (!SortedReplaces)
- return SortedReplaces.takeError();
-
- // We need to use lambda function here since there are two versions of
- // `reformat`.
- auto Reformat = [](const FormatStyle &Style, StringRef Code,
- std::vector<tooling::Range> Ranges,
- StringRef FileName) -> tooling::Replacements {
- return reformat(Style, Code, Ranges, FileName);
- };
- return processReplacements(Reformat, Code, *SortedReplaces, Style);
-}
-
-namespace {
-
-inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
- return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
- Replace.getLength() == 0 &&
- tooling::HeaderIncludes::IncludeRegex.match(
- Replace.getReplacementText());
-}
-
-inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
- return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
- Replace.getLength() == 1;
-}
-
-// FIXME: insert empty lines between newly created blocks.
-tooling::Replacements
-fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
- const FormatStyle &Style) {
- if (!Style.isCpp())
- return Replaces;
-
- tooling::Replacements HeaderInsertions;
- std::set<StringRef> HeadersToDelete;
- tooling::Replacements Result;
- for (const auto &R : Replaces) {
- if (isHeaderInsertion(R)) {
- // Replacements from \p Replaces must be conflict-free already, so we can
- // simply consume the error.
- consumeError(HeaderInsertions.add(R));
- } else if (isHeaderDeletion(R)) {
- HeadersToDelete.insert(R.getReplacementText());
- } else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
- llvm::errs() << "Insertions other than header #include insertion are "
- "not supported! "
- << R.getReplacementText() << "\n";
- } else {
- consumeError(Result.add(R));
- }
- }
- if (HeaderInsertions.empty() && HeadersToDelete.empty())
- return Replaces;
-
- StringRef FileName = Replaces.begin()->getFilePath();
- tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
-
- for (const auto &Header : HeadersToDelete) {
- tooling::Replacements Replaces =
- Includes.remove(Header.trim("\"<>"), Header.starts_with("<"));
- for (const auto &R : Replaces) {
- auto Err = Result.add(R);
- if (Err) {
- // Ignore the deletion on conflict.
- llvm::errs() << "Failed to add header deletion replacement for "
- << Header << ": " << toString(std::move(Err)) << "\n";
- }
- }
- }
-
- SmallVector<StringRef, 4> Matches;
- for (const auto &R : HeaderInsertions) {
- auto IncludeDirective = R.getReplacementText();
- bool Matched =
- tooling::HeaderIncludes::IncludeRegex.match(IncludeDirective, &Matches);
- assert(Matched && "Header insertion replacement must have replacement text "
- "'#include ...'");
- (void)Matched;
- auto IncludeName = Matches[2];
- auto Replace =
- Includes.insert(IncludeName.trim("\"<>"), IncludeName.starts_with("<"),
- tooling::IncludeDirective::Include);
- if (Replace) {
- auto Err = Result.add(*Replace);
- if (Err) {
- consumeError(std::move(Err));
- unsigned NewOffset =
- Result.getShiftedCodePosition(Replace->getOffset());
- auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
- Replace->getReplacementText());
- Result = Result.merge(tooling::Replacements(Shifted));
- }
- }
- }
- return Result;
-}
-
-} // anonymous namespace
-
-Expected<tooling::Replacements>
-cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
- const FormatStyle &Style) {
- // We need to use lambda function here since there are two versions of
- // `cleanup`.
- auto Cleanup = [](const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName) -> tooling::Replacements {
- return cleanup(Style, Code, Ranges, FileName);
- };
- // Make header insertion replacements insert new headers into correct blocks.
- tooling::Replacements NewReplaces =
- fixCppIncludeInsertions(Code, Replaces, Style);
- return cantFail(processReplacements(Cleanup, Code, NewReplaces, Style));
-}
-
-namespace internal {
-std::pair<tooling::Replacements, unsigned>
-reformat(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
- unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
- FormattingAttemptStatus *Status) {
- FormatStyle Expanded = Style;
- expandPresetsBraceWrapping(Expanded);
- expandPresetsSpaceBeforeParens(Expanded);
- expandPresetsSpacesInParens(Expanded);
-
- // These are handled by separate passes.
- Expanded.InsertBraces = false;
- Expanded.RemoveBracesLLVM = false;
- Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
- Expanded.RemoveSemicolon = false;
-
- // Make some sanity adjustments.
- switch (Expanded.RequiresClausePosition) {
- case FormatStyle::RCPS_SingleLine:
- case FormatStyle::RCPS_WithPreceding:
- Expanded.IndentRequiresClause = false;
- break;
- default:
- break;
- }
- if (Expanded.BraceWrapping.AfterEnum)
- Expanded.AllowShortEnumsOnASingleLine = false;
-
- if (Expanded.DisableFormat)
- return {tooling::Replacements(), 0};
- if (isLikelyXml(Code))
- return {tooling::Replacements(), 0};
- if (Expanded.isJavaScript() && isMpegTS(Code))
- return {tooling::Replacements(), 0};
-
- // JSON only needs the formatting passing.
- if (Style.isJson()) {
- std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
- auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
- NextStartColumn, LastStartColumn);
- if (!Env)
- return {};
- // Perform the actual formatting pass.
- tooling::Replacements Replaces =
- Formatter(*Env, Style, Status).process().first;
- // add a replacement to remove the "x = " from the result.
- if (Code.starts_with("x = ")) {
- Replaces = Replaces.merge(
- tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
- }
- // apply the reformatting changes and the removal of "x = ".
- if (applyAllReplacements(Code, Replaces))
- return {Replaces, 0};
- return {tooling::Replacements(), 0};
- }
-
- auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
- NextStartColumn, LastStartColumn);
- if (!Env)
- return {};
-
- typedef std::function<std::pair<tooling::Replacements, unsigned>(
- const Environment &)>
- AnalyzerPass;
-
- SmallVector<AnalyzerPass, 16> Passes;
-
- Passes.emplace_back([&](const Environment &Env) {
- return IntegerLiteralSeparatorFixer().process(Env, Expanded);
- });
-
- Passes.emplace_back([&](const Environment &Env) {
- return NumericLiteralCaseFixer().process(Env, Expanded);
- });
-
- if (Style.isCpp()) {
- if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
- addQualifierAlignmentFixerPasses(Expanded, Passes);
-
- if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
- FormatStyle S = Expanded;
- S.RemoveParentheses = Style.RemoveParentheses;
- Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
- return ParensRemover(Env, S).process(/*SkipAnnotation=*/true);
- });
- }
-
- if (Style.InsertBraces) {
- FormatStyle S = Expanded;
- S.InsertBraces = true;
- Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
- return BracesInserter(Env, S).process(/*SkipAnnotation=*/true);
- });
- }
-
- if (Style.RemoveBracesLLVM) {
- FormatStyle S = Expanded;
- S.RemoveBracesLLVM = true;
- Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
- return BracesRemover(Env, S).process(/*SkipAnnotation=*/true);
- });
- }
-
- if (Style.RemoveSemicolon) {
- FormatStyle S = Expanded;
- S.RemoveSemicolon = true;
- Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
- return SemiRemover(Env, S).process();
- });
- }
-
- if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
- Passes.emplace_back([&](const Environment &Env) {
- return EnumTrailingCommaEditor(Env, Expanded)
- .process(/*SkipAnnotation=*/true);
- });
- }
-
- if (Style.FixNamespaceComments) {
- Passes.emplace_back([&](const Environment &Env) {
- return NamespaceEndCommentsFixer(Env, Expanded).process();
- });
- }
-
- if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
- Passes.emplace_back([&](const Environment &Env) {
- return UsingDeclarationsSorter(Env, Expanded).process();
- });
- }
- }
-
- if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
- Passes.emplace_back([&](const Environment &Env) {
- return DefinitionBlockSeparator(Env, Expanded).process();
- });
- }
-
- if (Style.Language == FormatStyle::LK_ObjC &&
- !Style.ObjCPropertyAttributeOrder.empty()) {
- Passes.emplace_back([&](const Environment &Env) {
- return ObjCPropertyAttributeOrderFixer(Env, Expanded).process();
- });
- }
-
- if (Style.isJavaScript() &&
- Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
- Passes.emplace_back([&](const Environment &Env) {
- return JavaScriptRequoter(Env, Expanded).process(/*SkipAnnotation=*/true);
- });
- }
-
- Passes.emplace_back([&](const Environment &Env) {
- return Formatter(Env, Expanded, Status).process();
- });
-
- if (Style.isJavaScript() &&
- Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
- Passes.emplace_back([&](const Environment &Env) {
- return TrailingCommaInserter(Env, Expanded).process();
- });
- }
-
- std::optional<std::string> CurrentCode;
- tooling::Replacements Fixes;
- unsigned Penalty = 0;
- for (size_t I = 0, E = Passes.size(); I < E; ++I) {
- std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
- auto NewCode = applyAllReplacements(
- CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
- if (NewCode) {
- Fixes = Fixes.merge(PassFixes.first);
- Penalty += PassFixes.second;
- if (I + 1 < E) {
- CurrentCode = std::move(*NewCode);
- Env = Environment::make(
- *CurrentCode, FileName,
- tooling::calculateRangesAfterReplacements(Fixes, Ranges),
- FirstStartColumn, NextStartColumn, LastStartColumn);
- if (!Env)
- return {};
- }
- }
- }
-
- if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
- // Don't make replacements that replace nothing. QualifierAlignment can
- // produce them if one of its early passes changes e.g. `const volatile` to
- // `volatile const` and then a later pass changes it back again.
- tooling::Replacements NonNoOpFixes;
- for (const tooling::Replacement &Fix : Fixes) {
- StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
- if (OriginalCode != Fix.getReplacementText()) {
- auto Err = NonNoOpFixes.add(Fix);
- if (Err) {
- llvm::errs() << "Error adding replacements : "
- << toString(std::move(Err)) << "\n";
- }
- }
- }
- Fixes = std::move(NonNoOpFixes);
- }
-
- return {Fixes, Penalty};
-}
-} // namespace internal
-
-tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName,
- FormattingAttemptStatus *Status) {
- return internal::reformat(Style, Code, Ranges,
- /*FirstStartColumn=*/0,
- /*NextStartColumn=*/0,
- /*LastStartColumn=*/0, FileName, Status)
- .first;
-}
-
-tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName) {
- // cleanups only apply to C++ (they mostly concern ctor commas etc.)
- if (Style.Language != FormatStyle::LK_Cpp)
- return tooling::Replacements();
- auto Env = Environment::make(Code, FileName, Ranges);
- if (!Env)
- return {};
- return Cleaner(*Env, Style).process().first;
-}
-
-tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName, bool *IncompleteFormat) {
- FormattingAttemptStatus Status;
- auto Result = reformat(Style, Code, Ranges, FileName, &Status);
- if (!Status.FormatComplete)
- *IncompleteFormat = true;
- return Result;
-}
-
-tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
- StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName) {
- auto Env = Environment::make(Code, FileName, Ranges);
- if (!Env)
- return {};
- return NamespaceEndCommentsFixer(*Env, Style).process().first;
-}
-
-tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
- StringRef Code,
- ArrayRef<tooling::Range> Ranges,
- StringRef FileName) {
- auto Env = Environment::make(Code, FileName, Ranges);
- if (!Env)
- return {};
- return UsingDeclarationsSorter(*Env, Style).process().first;
-}
-
-LangOptions getFormattingLangOpts(const FormatStyle &Style) {
- LangOptions LangOpts;
-
- auto LexingStd = Style.Standard;
- if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
- LexingStd = FormatStyle::LS_Cpp20;
-
- const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
- const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
-
- switch (Style.Language) {
- case FormatStyle::LK_C:
- LangOpts.C11 = 1;
- LangOpts.C23 = 1;
- break;
- case FormatStyle::LK_Cpp:
- case FormatStyle::LK_ObjC:
- LangOpts.CXXOperatorNames = 1;
- LangOpts.CPlusPlus11 = SinceCpp11;
- LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
- LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
- LangOpts.CPlusPlus20 = SinceCpp20;
- [[fallthrough]];
- default:
- LangOpts.CPlusPlus = 1;
- }
-
- LangOpts.Char8 = SinceCpp20;
- LangOpts.AllowLiteralDigitSeparator = LangOpts.CPlusPlus14 || LangOpts.C23;
- // Turning on digraphs in standards before C++0x is error-prone, because e.g.
- // the sequence "<::" will be unconditionally treated as "[:".
- // Cf. Lexer::LexTokenInternal.
- LangOpts.Digraphs = SinceCpp11;
-
- LangOpts.LineComment = 1;
- LangOpts.Bool = 1;
- LangOpts.ObjC = 1;
- LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
- LangOpts.DeclSpecKeyword = 1; // To get __declspec.
- LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
-
- return LangOpts;
-}
-
-const char *StyleOptionHelpDescription =
- "Set coding style. <string> can be:\n"
- "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
- " Mozilla, WebKit.\n"
- "2. 'file' to load style configuration from a\n"
- " .clang-format file in one of the parent directories\n"
- " of the source file (for stdin, see --assume-filename).\n"
- " If no .clang-format file is found, falls back to\n"
- " --fallback-style.\n"
- " --style=file is the default.\n"
- "3. 'file:<format_file_path>' to explicitly specify\n"
- " the configuration file.\n"
- "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
- " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
-
-static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
- if (FileName.ends_with(".c"))
- return FormatStyle::LK_C;
- if (FileName.ends_with(".java"))
- return FormatStyle::LK_Java;
- if (FileName.ends_with_insensitive(".js") ||
- FileName.ends_with_insensitive(".mjs") ||
- FileName.ends_with_insensitive(".cjs") ||
- FileName.ends_with_insensitive(".ts")) {
- return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
- }
- if (FileName.ends_with(".m") || FileName.ends_with(".mm"))
- return FormatStyle::LK_ObjC;
- if (FileName.ends_with_insensitive(".proto") ||
- FileName.ends_with_insensitive(".protodevel")) {
- return FormatStyle::LK_Proto;
- }
- // txtpb is the canonical extension, and textproto is the legacy canonical
- // extension
- // https://protobuf.dev/reference/protobuf/textformat-spec/#text-format-files
- if (FileName.ends_with_insensitive(".txtpb") ||
- FileName.ends_with_insensitive(".textpb") ||
- FileName.ends_with_insensitive(".pb.txt") ||
- FileName.ends_with_insensitive(".textproto") ||
- FileName.ends_with_insensitive(".asciipb")) {
- return FormatStyle::LK_TextProto;
- }
- if (FileName.ends_with_insensitive(".td"))
- return FormatStyle::LK_TableGen;
- if (FileName.ends_with_insensitive(".cs"))
- return FormatStyle::LK_CSharp;
- if (FileName.ends_with_insensitive(".json") ||
- FileName.ends_with_insensitive(".ipynb")) {
- return FormatStyle::LK_Json;
- }
- if (FileName.ends_with_insensitive(".sv") ||
- FileName.ends_with_insensitive(".svh") ||
- FileName.ends_with_insensitive(".v") ||
- FileName.ends_with_insensitive(".vh")) {
- return FormatStyle::LK_Verilog;
- }
- return FormatStyle::LK_Cpp;
-}
-
-static FormatStyle::LanguageKind getLanguageByComment(const Environment &Env) {
- const auto ID = Env.getFileID();
- const auto &SourceMgr = Env.getSourceManager();
-
- LangOptions LangOpts;
- LangOpts.CPlusPlus = 1;
- LangOpts.LineComment = 1;
-
- Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
- Lex.SetCommentRetentionState(true);
-
- for (Token Tok; !Lex.LexFromRawLexer(Tok) && Tok.is(tok::comment);) {
- auto Text = StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
- Tok.getLength());
- if (!Text.consume_front("// clang-format Language:"))
- continue;
-
- Text = Text.trim();
- if (Text == "C")
- return FormatStyle::LK_C;
- if (Text == "Cpp")
- return FormatStyle::LK_Cpp;
- if (Text == "ObjC")
- return FormatStyle::LK_ObjC;
- }
-
- return FormatStyle::LK_None;
-}
-
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
- const auto GuessedLanguage = getLanguageByFileName(FileName);
- if (GuessedLanguage == FormatStyle::LK_Cpp) {
- auto Extension = llvm::sys::path::extension(FileName);
- // If there's no file extension (or it's .h), we need to check the contents
- // of the code to see if it contains Objective-C.
- if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
- auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
- Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
- if (const auto Language = getLanguageByComment(Env);
- Language != FormatStyle::LK_None) {
- return Language;
- }
- ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
- Guesser.process();
- if (Guesser.isObjC())
- return FormatStyle::LK_ObjC;
- }
- }
- return GuessedLanguage;
-}
-
-// Update StyleOptionHelpDescription above when changing this.
-const char *DefaultFormatStyle = "file";
-
-const char *DefaultFallbackStyle = "LLVM";
-
-llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
-loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
- FormatStyle *Style, bool AllowUnknownOptions,
- llvm::SourceMgr::DiagHandlerTy DiagHandler,
- bool IsDotHFile) {
- llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
- FS->getBufferForFile(ConfigFile.str());
- if (auto EC = Text.getError())
- return EC;
- if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
- DiagHandler, /*DiagHandlerCtx=*/nullptr,
- IsDotHFile)) {
- return EC;
- }
- return Text;
-}
-
-Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
- StringRef FallbackStyleName, StringRef Code,
- llvm::vfs::FileSystem *FS,
- bool AllowUnknownOptions,
- llvm::SourceMgr::DiagHandlerTy DiagHandler) {
- FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
- FormatStyle FallbackStyle = getNoStyle();
- if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
- return make_string_error("Invalid fallback style: " + FallbackStyleName);
-
- SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1> ChildFormatTextToApply;
-
- if (StyleName.starts_with("{")) {
- // Parse YAML/JSON style from the command line.
- StringRef Source = "<command-line>";
- if (std::error_code ec =
- parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
- AllowUnknownOptions, DiagHandler)) {
- return make_string_error("Error parsing -style: " + ec.message());
- }
-
- if (Style.InheritConfig.empty())
- return Style;
-
- ChildFormatTextToApply.emplace_back(
- llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
- }
-
- if (!FS)
- FS = llvm::vfs::getRealFileSystem().get();
- assert(FS);
-
- const bool IsDotHFile = FileName.ends_with(".h");
-
- // User provided clang-format file using -style=file:path/to/format/file.
- if (Style.InheritConfig.empty() &&
- StyleName.starts_with_insensitive("file:")) {
- auto ConfigFile = StyleName.substr(5);
- llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
- loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
- DiagHandler, IsDotHFile);
- if (auto EC = Text.getError()) {
- return make_string_error("Error reading " + ConfigFile + ": " +
- EC.message());
- }
-
- LLVM_DEBUG(llvm::dbgs()
- << "Using configuration file " << ConfigFile << "\n");
-
- if (Style.InheritConfig.empty())
- return Style;
-
- // Search for parent configs starting from the parent directory of
- // ConfigFile.
- FileName = ConfigFile;
- ChildFormatTextToApply.emplace_back(std::move(*Text));
- }
-
- // If the style inherits the parent configuration it is a command line
- // configuration, which wants to inherit, so we have to skip the check of the
- // StyleName.
- if (Style.InheritConfig.empty() && !StyleName.equals_insensitive("file")) {
- if (!getPredefinedStyle(StyleName, Style.Language, &Style))
- return make_string_error("Invalid value for -style");
- if (Style.InheritConfig.empty())
- return Style;
- }
-
- using namespace llvm::sys::path;
- using String = SmallString<128>;
-
- String Path(FileName);
- if (std::error_code EC = FS->makeAbsolute(Path))
- return make_string_error(EC.message());
-
- auto Normalize = [](String &Path) {
- Path = convert_to_slash(Path);
- remove_dots(Path, /*remove_dot_dot=*/true, Style::posix);
- };
-
- Normalize(Path);
-
- // Reset possible inheritance
- Style.InheritConfig.clear();
-
- auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-
- auto applyChildFormatTexts = [&](FormatStyle *Style) {
- for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
- auto EC =
- parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
- DiagHandler ? DiagHandler : dropDiagnosticHandler);
- // It was already correctly parsed.
- assert(!EC);
- static_cast<void>(EC);
- }
- };
-
- // Look for .clang-format/_clang-format file in the file's parent directories.
- SmallVector<std::string, 2> FilesToLookFor;
- FilesToLookFor.push_back(".clang-format");
- FilesToLookFor.push_back("_clang-format");
-
- llvm::StringSet<> Directories; // Inherited directories.
- bool Redirected = false;
- String Dir, UnsuitableConfigFiles;
- for (StringRef Directory = Path; !Directory.empty();
- Directory = Redirected ? Dir.str() : parent_path(Directory)) {
- auto Status = FS->status(Directory);
- if (!Status ||
- Status->getType() != llvm::sys::fs::file_type::directory_file) {
- if (!Redirected)
- continue;
- return make_string_error("Failed to inherit configuration directory " +
- Directory);
- }
-
- for (const auto &F : FilesToLookFor) {
- String ConfigFile(Directory);
-
- append(ConfigFile, F);
- LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
-
- Status = FS->status(ConfigFile);
- if (!Status ||
- Status->getType() != llvm::sys::fs::file_type::regular_file) {
- continue;
- }
-
- llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
- loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
- DiagHandler, IsDotHFile);
- if (auto EC = Text.getError()) {
- if (EC != ParseError::Unsuitable) {
- return make_string_error("Error reading " + ConfigFile + ": " +
- EC.message());
- }
- if (!UnsuitableConfigFiles.empty())
- UnsuitableConfigFiles.append(", ");
- UnsuitableConfigFiles.append(ConfigFile);
- continue;
- }
-
- LLVM_DEBUG(llvm::dbgs()
- << "Using configuration file " << ConfigFile << "\n");
-
- if (Style.InheritConfig.empty()) {
- if (!ChildFormatTextToApply.empty()) {
- LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
- applyChildFormatTexts(&Style);
- }
- return Style;
- }
-
- if (!Directories.insert(Directory).second) {
- return make_string_error(
- "Loop detected when inheriting configuration file in " + Directory);
- }
-
- LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
-
- if (Style.InheritConfig == "..") {
- Redirected = false;
- } else {
- Redirected = true;
- String ExpandedDir;
- llvm::sys::fs::expand_tilde(Style.InheritConfig, ExpandedDir);
- Normalize(ExpandedDir);
- if (is_absolute(ExpandedDir, Style::posix)) {
- Dir = ExpandedDir;
- } else {
- Dir = Directory.str();
- append(Dir, Style::posix, ExpandedDir);
- }
- }
-
- // Reset inheritance of style
- Style.InheritConfig.clear();
-
- ChildFormatTextToApply.emplace_back(std::move(*Text));
-
- // Breaking out of the inner loop, since we don't want to parse
- // .clang-format AND _clang-format, if both exist. Then we continue the
- // outer loop (parent directories) in search for the parent
- // configuration.
- break;
- }
- }
-
- if (!UnsuitableConfigFiles.empty()) {
- return make_string_error("Configuration file(s) do(es) not support " +
- getLanguageName(Style.Language) + ": " +
- UnsuitableConfigFiles);
- }
-
- if (!ChildFormatTextToApply.empty()) {
- LLVM_DEBUG(llvm::dbgs()
- << "Applying child configurations on fallback style\n");
- applyChildFormatTexts(&FallbackStyle);
- }
-
- return FallbackStyle;
-}
-
-static bool isClangFormatOnOff(StringRef Comment, bool On) {
- if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
- return true;
-
- static const char ClangFormatOn[] = "// clang-format on";
- static const char ClangFormatOff[] = "// clang-format off";
- const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 1;
-
- return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
- (Comment.size() == Size || Comment[Size] == ':');
-}
-
-bool isClangFormatOn(StringRef Comment) {
- return isClangFormatOnOff(Comment, /*On=*/true);
-}
-
-bool isClangFormatOff(StringRef Comment) {
- return isClangFormatOnOff(Comment, /*On=*/false);
-}
-
-} // namespace format
-} // namespace clang
+//===--- Format.cpp - Format C++ code -------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file implements functions declared in Format.h. This will be
+/// split into separate files as we go.
+///
+//===----------------------------------------------------------------------===//
+
+#include "clang/Format/Format.h"
+#include "DefinitionBlockSeparator.h"
+#include "IntegerLiteralSeparatorFixer.h"
+#include "NamespaceEndCommentsFixer.h"
+#include "NumericLiteralCaseFixer.h"
+#include "ObjCPropertyAttributeOrderFixer.h"
+#include "QualifierAlignmentFixer.h"
+#include "SortJavaScriptImports.h"
+#include "UnwrappedLineFormatter.h"
+#include "UsingDeclarationsSorter.h"
+#include "clang/Tooling/Inclusions/HeaderIncludes.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/StringSet.h"
+#include <limits>
+
+#define DEBUG_TYPE "format-formatter"
+
+using clang::format::FormatStyle;
+
+LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
+LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::BinaryOperationBreakRule)
+LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tok::TokenKind)
+
+enum BracketAlignmentStyle : int8_t {
+ BAS_Align,
+ BAS_DontAlign,
+ BAS_AlwaysBreak,
+ BAS_BlockIndent
+};
+
+namespace llvm {
+namespace yaml {
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::BBNSS_Never);
+ IO.enumCase(Value, "OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
+ IO.enumCase(Value, "Always", FormatStyle::BBNSS_Always);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
+ static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::AlignConsecutiveStyle{});
+ IO.enumCase(Value, "Consecutive",
+ FormatStyle::AlignConsecutiveStyle(
+ {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
+ /*AcrossComments=*/false, /*AlignCompound=*/false,
+ /*AlignFunctionDeclarations=*/true,
+ /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
+ IO.enumCase(Value, "AcrossEmptyLines",
+ FormatStyle::AlignConsecutiveStyle(
+ {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
+ /*AcrossComments=*/false, /*AlignCompound=*/false,
+ /*AlignFunctionDeclarations=*/true,
+ /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
+ IO.enumCase(Value, "AcrossComments",
+ FormatStyle::AlignConsecutiveStyle(
+ {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
+ /*AcrossComments=*/true, /*AlignCompound=*/false,
+ /*AlignFunctionDeclarations=*/true,
+ /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
+ IO.enumCase(Value, "AcrossEmptyLinesAndComments",
+ FormatStyle::AlignConsecutiveStyle(
+ {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
+ /*AcrossComments=*/true, /*AlignCompound=*/false,
+ /*AlignFunctionDeclarations=*/true,
+ /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true",
+ FormatStyle::AlignConsecutiveStyle(
+ {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
+ /*AcrossComments=*/false, /*AlignCompound=*/false,
+ /*AlignFunctionDeclarations=*/true,
+ /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
+ IO.enumCase(Value, "false", FormatStyle::AlignConsecutiveStyle{});
+ }
+
+ static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
+ IO.mapOptional("Enabled", Value.Enabled);
+ IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
+ IO.mapOptional("AcrossComments", Value.AcrossComments);
+ IO.mapOptional("AlignCompound", Value.AlignCompound);
+ IO.mapOptional("AlignFunctionDeclarations",
+ Value.AlignFunctionDeclarations);
+ IO.mapOptional("AlignFunctionPointers", Value.AlignFunctionPointers);
+ IO.mapOptional("PadOperators", Value.PadOperators);
+ }
+};
+
+template <>
+struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
+ static void mapping(IO &IO,
+ FormatStyle::ShortCaseStatementsAlignmentStyle &Value) {
+ IO.mapOptional("Enabled", Value.Enabled);
+ IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
+ IO.mapOptional("AcrossComments", Value.AcrossComments);
+ IO.mapOptional("AlignCaseArrows", Value.AlignCaseArrows);
+ IO.mapOptional("AlignCaseColons", Value.AlignCaseColons);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
+ static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value) {
+ IO.enumCase(Value, "Always", FormatStyle::ABS_Always);
+ IO.enumCase(Value, "Leave", FormatStyle::ABS_Leave);
+ IO.enumCase(Value, "LeaveAll", FormatStyle::ABS_LeaveAll);
+ IO.enumCase(Value, "Never", FormatStyle::ABS_Never);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::ArrayInitializerAlignmentStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::AIAS_None);
+ IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
+ IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
+ static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
+ IO.enumCase(Value, "All", FormatStyle::BOS_All);
+ IO.enumCase(Value, "true", FormatStyle::BOS_All);
+ IO.enumCase(Value, "None", FormatStyle::BOS_None);
+ IO.enumCase(Value, "false", FormatStyle::BOS_None);
+ IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
+ static void enumeration(IO &IO, FormatStyle::BinPackParametersStyle &Value) {
+ IO.enumCase(Value, "BinPack", FormatStyle::BPPS_BinPack);
+ IO.enumCase(Value, "OnePerLine", FormatStyle::BPPS_OnePerLine);
+ IO.enumCase(Value, "AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::BPPS_BinPack);
+ IO.enumCase(Value, "false", FormatStyle::BPPS_OnePerLine);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
+ static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
+ IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
+ IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
+ IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BitFieldColonSpacingStyle &Value) {
+ IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
+ IO.enumCase(Value, "None", FormatStyle::BFCS_None);
+ IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
+ IO.enumCase(Value, "After", FormatStyle::BFCS_After);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
+ static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
+ IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
+ IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
+ IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
+ IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
+ IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
+ IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
+ IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
+ IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
+ IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
+ static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
+ IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
+ IO.mapOptional("AfterClass", Wrapping.AfterClass);
+ IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
+ IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
+ IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
+ IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
+ IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
+ IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
+ IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
+ IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
+ IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
+ IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
+ IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
+ IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
+ IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
+ IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
+ IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
+ IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<BracketAlignmentStyle> {
+ static void enumeration(IO &IO, BracketAlignmentStyle &Value) {
+ IO.enumCase(Value, "Align", BAS_Align);
+ IO.enumCase(Value, "DontAlign", BAS_DontAlign);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", BAS_Align);
+ IO.enumCase(Value, "false", BAS_DontAlign);
+ IO.enumCase(Value, "AlwaysBreak", BAS_AlwaysBreak);
+ IO.enumCase(Value, "BlockIndent", BAS_BlockIndent);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<
+ FormatStyle::BraceWrappingAfterControlStatementStyle> {
+ static void
+ enumeration(IO &IO,
+ FormatStyle::BraceWrappingAfterControlStatementStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
+ IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
+ IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
+ IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<
+ FormatStyle::BreakBeforeConceptDeclarationsStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::BBCDS_Never);
+ IO.enumCase(Value, "Allowed", FormatStyle::BBCDS_Allowed);
+ IO.enumCase(Value, "Always", FormatStyle::BBCDS_Always);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::BBCDS_Always);
+ IO.enumCase(Value, "false", FormatStyle::BBCDS_Allowed);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BreakBeforeInlineASMColonStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
+ IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
+ IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BreakBinaryOperationsStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::BBO_Never);
+ IO.enumCase(Value, "OnePerLine", FormatStyle::BBO_OnePerLine);
+ IO.enumCase(Value, "RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
+ }
+};
+
+template <> struct ScalarTraits<clang::tok::TokenKind> {
+ static void output(const clang::tok::TokenKind &Value, void *,
+ llvm::raw_ostream &Out) {
+ if (const char *Spelling = clang::tok::getPunctuatorSpelling(Value))
+ Out << Spelling;
+ else
+ Out << clang::tok::getTokenName(Value);
+ }
+
+ static StringRef input(StringRef Scalar, void *,
+ clang::tok::TokenKind &Value) {
+ // Map operator spelling strings to tok::TokenKind.
+#define PUNCTUATOR(Name, Spelling) \
+ if (Scalar == Spelling) { \
+ Value = clang::tok::Name; \
+ return {}; \
+ }
+#include "clang/Basic/TokenKinds.def"
+ return "unknown operator";
+ }
+
+ static QuotingType mustQuote(StringRef) { return QuotingType::None; }
+};
+
+template <> struct MappingTraits<FormatStyle::BinaryOperationBreakRule> {
+ static void mapping(IO &IO, FormatStyle::BinaryOperationBreakRule &Value) {
+ IO.mapOptional("Operators", Value.Operators);
+ // Default to OnePerLine since a per-operator rule with Never is a no-op.
+ if (!IO.outputting())
+ Value.Style = FormatStyle::BBO_OnePerLine;
+ IO.mapOptional("Style", Value.Style);
+ IO.mapOptional("MinChainLength", Value.MinChainLength);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::BreakBinaryOperationsOptions> {
+ static void enumInput(IO &IO,
+ FormatStyle::BreakBinaryOperationsOptions &Value) {
+ IO.enumCase(Value, "Never",
+ FormatStyle::BreakBinaryOperationsOptions(
+ {FormatStyle::BBO_Never, {}}));
+ IO.enumCase(Value, "OnePerLine",
+ FormatStyle::BreakBinaryOperationsOptions(
+ {FormatStyle::BBO_OnePerLine, {}}));
+ IO.enumCase(Value, "RespectPrecedence",
+ FormatStyle::BreakBinaryOperationsOptions(
+ {FormatStyle::BBO_RespectPrecedence, {}}));
+ }
+
+ static void mapping(IO &IO,
+ FormatStyle::BreakBinaryOperationsOptions &Value) {
+ IO.mapOptional("Default", Value.Default);
+ IO.mapOptional("PerOperator", Value.PerOperator);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
+ IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
+ IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
+ IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
+ IO.enumCase(Value, "AfterComma", FormatStyle::BCIS_AfterComma);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BreakInheritanceListStyle &Value) {
+ IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
+ IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
+ IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
+ IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BreakTemplateDeclarationsStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::BTDS_Leave);
+ IO.enumCase(Value, "No", FormatStyle::BTDS_No);
+ IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
+ IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
+ IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
+ static void enumeration(IO &IO, FormatStyle::BracedListStyle &Value) {
+ IO.enumCase(Value, "Block", FormatStyle::BLS_Block);
+ IO.enumCase(Value, "FunctionCall", FormatStyle::BLS_FunctionCall);
+ IO.enumCase(Value, "AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::BLS_Block);
+ IO.enumCase(Value, "true", FormatStyle::BLS_AlignFirstComment);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
+ static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value) {
+ IO.enumCase(Value, "DontBreak", FormatStyle::DAS_DontBreak);
+ IO.enumCase(Value, "BreakElements", FormatStyle::DAS_BreakElements);
+ IO.enumCase(Value, "BreakAll", FormatStyle::DAS_BreakAll);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
+ IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
+ IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
+ IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::EscapedNewlineAlignmentStyle &Value) {
+ IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
+ IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
+ IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
+ IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
+ IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
+ IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
+ IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<
+ FormatStyle::EmptyLineBeforeAccessModifierStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
+ IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
+ IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
+ IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
+ static void enumeration(IO &IO, FormatStyle::EnumTrailingCommaStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::ETC_Leave);
+ IO.enumCase(Value, "Insert", FormatStyle::ETC_Insert);
+ IO.enumCase(Value, "Remove", FormatStyle::ETC_Remove);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
+ static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value) {
+ IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
+ IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
+ IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
+ IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
+ IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
+ static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base) {
+ IO.mapOptional("Binary", Base.Binary);
+ IO.mapOptional("BinaryMinDigitsInsert", Base.BinaryMinDigitsInsert);
+ IO.mapOptional("BinaryMaxDigitsRemove", Base.BinaryMaxDigitsRemove);
+ IO.mapOptional("Decimal", Base.Decimal);
+ IO.mapOptional("DecimalMinDigitsInsert", Base.DecimalMinDigitsInsert);
+ IO.mapOptional("DecimalMaxDigitsRemove", Base.DecimalMaxDigitsRemove);
+ IO.mapOptional("Hex", Base.Hex);
+ IO.mapOptional("HexMinDigitsInsert", Base.HexMinDigitsInsert);
+ IO.mapOptional("HexMaxDigitsRemove", Base.HexMaxDigitsRemove);
+
+ // For backward compatibility.
+ IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigitsInsert);
+ IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigitsInsert);
+ IO.mapOptional("HexMinDigits", Base.HexMinDigitsInsert);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
+ static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
+ IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
+ IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
+ static void mapping(IO &IO, FormatStyle::KeepEmptyLinesStyle &Value) {
+ IO.mapOptional("AtEndOfFile", Value.AtEndOfFile);
+ IO.mapOptional("AtStartOfBlock", Value.AtStartOfBlock);
+ IO.mapOptional("AtStartOfFile", Value.AtStartOfFile);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
+ static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
+ IO.enumCase(Value, "C", FormatStyle::LK_C);
+ IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
+ IO.enumCase(Value, "Java", FormatStyle::LK_Java);
+ IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
+ IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
+ IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
+ IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
+ IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
+ IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
+ IO.enumCase(Value, "Json", FormatStyle::LK_Json);
+ IO.enumCase(Value, "Verilog", FormatStyle::LK_Verilog);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
+ static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
+ IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
+ IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
+ IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
+
+ IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
+ IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
+
+ IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
+ IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
+ IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
+
+ IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
+ IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
+ IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
+ static void enumeration(IO &IO,
+ FormatStyle::LambdaBodyIndentationKind &Value) {
+ IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
+ IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
+ static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value) {
+ IO.enumCase(Value, "LF", FormatStyle::LE_LF);
+ IO.enumCase(Value, "CRLF", FormatStyle::LE_CRLF);
+ IO.enumCase(Value, "DeriveLF", FormatStyle::LE_DeriveLF);
+ IO.enumCase(Value, "DeriveCRLF", FormatStyle::LE_DeriveCRLF);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
+ static void enumeration(IO &IO,
+ FormatStyle::NamespaceIndentationKind &Value) {
+ IO.enumCase(Value, "None", FormatStyle::NI_None);
+ IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
+ IO.enumCase(Value, "All", FormatStyle::NI_All);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::NumericLiteralComponentStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::NLCS_Leave);
+ IO.enumCase(Value, "Upper", FormatStyle::NLCS_Upper);
+ IO.enumCase(Value, "Lower", FormatStyle::NLCS_Lower);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
+ static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &Value) {
+ IO.mapOptional("ExponentLetter", Value.ExponentLetter);
+ IO.mapOptional("HexDigit", Value.HexDigit);
+ IO.mapOptional("Prefix", Value.Prefix);
+ IO.mapOptional("Suffix", Value.Suffix);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
+ static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value) {
+ IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
+ IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
+ IO.enumCase(Value, "AlignAfterOperator",
+ FormatStyle::OAS_AlignAfterOperator);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::OAS_Align);
+ IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
+ IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
+ IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
+ IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
+ IO.enumCase(Value, "NextLineOnly", FormatStyle::PCIS_NextLineOnly);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
+ static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
+ IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
+ IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
+ IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::PAS_Left);
+ IO.enumCase(Value, "false", FormatStyle::PAS_Right);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
+ static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
+ IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
+ IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
+ IO.enumCase(Value, "Leave", FormatStyle::PPDIS_Leave);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
+ static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
+ IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
+ IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
+ IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::RawStringFormat> {
+ static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
+ IO.mapOptional("Language", Format.Language);
+ IO.mapOptional("Delimiters", Format.Delimiters);
+ IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
+ IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
+ IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
+ static void enumeration(IO &IO, FormatStyle::ReflowCommentsStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::RCS_Never);
+ IO.enumCase(Value, "IndentOnly", FormatStyle::RCS_IndentOnly);
+ IO.enumCase(Value, "Always", FormatStyle::RCS_Always);
+ // For backward compatibility:
+ IO.enumCase(Value, "false", FormatStyle::RCS_Never);
+ IO.enumCase(Value, "true", FormatStyle::RCS_Always);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
+ static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value) {
+ IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
+ IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
+ IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
+ IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
+ static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::RPS_Leave);
+ IO.enumCase(Value, "MultipleParentheses",
+ FormatStyle::RPS_MultipleParentheses);
+ IO.enumCase(Value, "ReturnStatement", FormatStyle::RPS_ReturnStatement);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::RequiresClausePositionStyle &Value) {
+ IO.enumCase(Value, "OwnLine", FormatStyle::RCPS_OwnLine);
+ IO.enumCase(Value, "OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
+ IO.enumCase(Value, "WithPreceding", FormatStyle::RCPS_WithPreceding);
+ IO.enumCase(Value, "WithFollowing", FormatStyle::RCPS_WithFollowing);
+ IO.enumCase(Value, "SingleLine", FormatStyle::RCPS_SingleLine);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
+ static void
+ enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value) {
+ IO.enumCase(Value, "Keyword", FormatStyle::REI_Keyword);
+ IO.enumCase(Value, "OuterScope", FormatStyle::REI_OuterScope);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
+ static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::RTBS_None);
+ IO.enumCase(Value, "Automatic", FormatStyle::RTBS_Automatic);
+ IO.enumCase(Value, "ExceptShortType", FormatStyle::RTBS_ExceptShortType);
+ IO.enumCase(Value, "All", FormatStyle::RTBS_All);
+ IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
+ IO.enumCase(Value, "TopLevelDefinitions",
+ FormatStyle::RTBS_TopLevelDefinitions);
+ IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
+ static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
+ IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
+ IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
+ static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
+ IO.enumCase(Value, "false", FormatStyle::SBS_Never);
+ IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
+ IO.enumCase(Value, "true", FormatStyle::SBS_Always);
+ IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::ShortFunctionStyle> {
+ static void enumInput(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::ShortFunctionStyle());
+ IO.enumCase(Value, "Empty",
+ FormatStyle::ShortFunctionStyle::setEmptyOnly());
+ IO.enumCase(Value, "Inline",
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline());
+ IO.enumCase(Value, "InlineOnly",
+ FormatStyle::ShortFunctionStyle::setInlineOnly());
+ IO.enumCase(Value, "All", FormatStyle::ShortFunctionStyle::setAll());
+
+ // For backward compatibility.
+ IO.enumCase(Value, "true", FormatStyle::ShortFunctionStyle::setAll());
+ IO.enumCase(Value, "false", FormatStyle::ShortFunctionStyle());
+ }
+
+ static void mapping(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
+ IO.mapOptional("Empty", Value.Empty);
+ IO.mapOptional("Inline", Value.Inline);
+ IO.mapOptional("Other", Value.Other);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
+ static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
+ IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
+ IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
+ IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
+ IO.enumCase(Value, "false", FormatStyle::SIS_Never);
+ IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
+ static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::SLS_None);
+ IO.enumCase(Value, "false", FormatStyle::SLS_None);
+ IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
+ IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
+ IO.enumCase(Value, "All", FormatStyle::SLS_All);
+ IO.enumCase(Value, "true", FormatStyle::SLS_All);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::ShortRecordStyle> {
+ static void enumeration(IO &IO, FormatStyle::ShortRecordStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SRS_Never);
+ IO.enumCase(Value, "EmptyAndAttached", FormatStyle::SRS_EmptyAndAttached);
+ IO.enumCase(Value, "Empty", FormatStyle::SRS_Empty);
+ IO.enumCase(Value, "Always", FormatStyle::SRS_Always);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::SortIncludesOptions> {
+ static void enumInput(IO &IO, FormatStyle::SortIncludesOptions &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SortIncludesOptions{});
+ IO.enumCase(Value, "CaseInsensitive",
+ FormatStyle::SortIncludesOptions{/*Enabled=*/true,
+ /*IgnoreCase=*/true,
+ /*IgnoreExtension=*/false});
+ IO.enumCase(Value, "CaseSensitive",
+ FormatStyle::SortIncludesOptions{/*Enabled=*/true,
+ /*IgnoreCase=*/false,
+ /*IgnoreExtension=*/false});
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::SortIncludesOptions{});
+ IO.enumCase(Value, "true",
+ FormatStyle::SortIncludesOptions{/*Enabled=*/true,
+ /*IgnoreCase=*/false,
+ /*IgnoreExtension=*/false});
+ }
+
+ static void mapping(IO &IO, FormatStyle::SortIncludesOptions &Value) {
+ IO.mapOptional("Enabled", Value.Enabled);
+ IO.mapOptional("IgnoreCase", Value.IgnoreCase);
+ IO.mapOptional("IgnoreExtension", Value.IgnoreExtension);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
+ static void enumeration(IO &IO,
+ FormatStyle::SortJavaStaticImportOptions &Value) {
+ IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
+ IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
+ static void enumeration(IO &IO,
+ FormatStyle::SortUsingDeclarationsOptions &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SUD_Never);
+ IO.enumCase(Value, "Lexicographic", FormatStyle::SUD_Lexicographic);
+ IO.enumCase(Value, "LexicographicNumeric",
+ FormatStyle::SUD_LexicographicNumeric);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::SUD_Never);
+ IO.enumCase(Value, "true", FormatStyle::SUD_LexicographicNumeric);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
+ static void
+ enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value) {
+ IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
+ IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
+ IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
+ IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
+ static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
+ IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
+ IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
+ IO.mapOptional("AfterFunctionDefinitionName",
+ Spacing.AfterFunctionDefinitionName);
+ IO.mapOptional("AfterFunctionDeclarationName",
+ Spacing.AfterFunctionDeclarationName);
+ IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
+ IO.mapOptional("AfterNot", Spacing.AfterNot);
+ IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
+ IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
+ IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
+ IO.mapOptional("AfterRequiresInExpression",
+ Spacing.AfterRequiresInExpression);
+ IO.mapOptional("BeforeNonEmptyParentheses",
+ Spacing.BeforeNonEmptyParentheses);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
+ static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
+ IO.enumCase(Value, "ControlStatements",
+ FormatStyle::SBPO_ControlStatements);
+ IO.enumCase(Value, "ControlStatementsExceptControlMacros",
+ FormatStyle::SBPO_ControlStatementsExceptControlMacros);
+ IO.enumCase(Value, "NonEmptyParentheses",
+ FormatStyle::SBPO_NonEmptyParentheses);
+ IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
+ IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
+ IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
+ IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
+ FormatStyle::SBPO_ControlStatementsExceptControlMacros);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
+ static void enumeration(IO &IO, FormatStyle::SpaceInEmptyBracesStyle &Value) {
+ IO.enumCase(Value, "Always", FormatStyle::SIEB_Always);
+ IO.enumCase(Value, "Block", FormatStyle::SIEB_Block);
+ IO.enumCase(Value, "Never", FormatStyle::SIEB_Never);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
+ static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
+ IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
+ IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
+ IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
+ static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
+ // Transform the maximum to signed, to parse "-1" correctly
+ int signedMaximum = static_cast<int>(Space.Maximum);
+ IO.mapOptional("Minimum", Space.Minimum);
+ IO.mapOptional("Maximum", signedMaximum);
+ Space.Maximum = static_cast<unsigned>(signedMaximum);
+
+ if (Space.Maximum < std::numeric_limits<unsigned>::max())
+ Space.Minimum = std::min(Space.Minimum, Space.Maximum);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {
+ static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
+ IO.mapOptional("ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
+ IO.mapOptional("InCStyleCasts", Spaces.InCStyleCasts);
+ IO.mapOptional("InConditionalStatements", Spaces.InConditionalStatements);
+ IO.mapOptional("InEmptyParentheses", Spaces.InEmptyParentheses);
+ IO.mapOptional("Other", Spaces.Other);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
+ static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::SIPO_Never);
+ IO.enumCase(Value, "Custom", FormatStyle::SIPO_Custom);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
+ static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value) {
+ IO.enumCase(Value, "None", FormatStyle::TCS_None);
+ IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
+ static void enumeration(IO &IO,
+ FormatStyle::TrailingCommentsAlignmentKinds &Value) {
+ IO.enumCase(Value, "Leave", FormatStyle::TCAS_Leave);
+ IO.enumCase(Value, "Always", FormatStyle::TCAS_Always);
+ IO.enumCase(Value, "Never", FormatStyle::TCAS_Never);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
+ static void enumInput(IO &IO,
+ FormatStyle::TrailingCommentsAlignmentStyle &Value) {
+ IO.enumCase(Value, "Leave",
+ FormatStyle::TrailingCommentsAlignmentStyle(
+ {FormatStyle::TCAS_Leave, 0, true}));
+
+ IO.enumCase(Value, "Always",
+ FormatStyle::TrailingCommentsAlignmentStyle(
+ {FormatStyle::TCAS_Always, 0, true}));
+
+ IO.enumCase(Value, "Never",
+ FormatStyle::TrailingCommentsAlignmentStyle(
+ {FormatStyle::TCAS_Never, 0, true}));
+
+ // For backwards compatibility
+ IO.enumCase(Value, "true",
+ FormatStyle::TrailingCommentsAlignmentStyle(
+ {FormatStyle::TCAS_Always, 0, true}));
+ IO.enumCase(Value, "false",
+ FormatStyle::TrailingCommentsAlignmentStyle(
+ {FormatStyle::TCAS_Never, 0, true}));
+ }
+
+ static void mapping(IO &IO,
+ FormatStyle::TrailingCommentsAlignmentStyle &Value) {
+ IO.mapOptional("AlignPPAndNotPP", Value.AlignPPAndNotPP);
+ IO.mapOptional("Kind", Value.Kind);
+ IO.mapOptional("OverEmptyLines", Value.OverEmptyLines);
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
+ static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::UT_Never);
+ IO.enumCase(Value, "false", FormatStyle::UT_Never);
+ IO.enumCase(Value, "Always", FormatStyle::UT_Always);
+ IO.enumCase(Value, "true", FormatStyle::UT_Always);
+ IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
+ IO.enumCase(Value, "ForContinuationAndIndentation",
+ FormatStyle::UT_ForContinuationAndIndentation);
+ IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<
+ FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
+ static void
+ enumeration(IO &IO,
+ FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value) {
+ IO.enumCase(Value, "Never", FormatStyle::WNBWELS_Never);
+ IO.enumCase(Value, "Always", FormatStyle::WNBWELS_Always);
+ IO.enumCase(Value, "Leave", FormatStyle::WNBWELS_Leave);
+ }
+};
+
+template <> struct MappingTraits<FormatStyle> {
+ static void mapping(IO &IO, FormatStyle &Style) {
+ // When reading, read the language first, we need it for getPredefinedStyle.
+ IO.mapOptional("Language", Style.Language);
+
+ StringRef BasedOnStyle;
+ if (IO.outputting()) {
+ StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
+ "WebKit", "GNU", "Microsoft", "clang-format"};
+ for (StringRef StyleName : Styles) {
+ FormatStyle PredefinedStyle;
+ if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
+ Style == PredefinedStyle) {
+ BasedOnStyle = StyleName;
+ break;
+ }
+ }
+ } else {
+ IO.mapOptional("BasedOnStyle", BasedOnStyle);
+ if (!BasedOnStyle.empty()) {
+ FormatStyle::LanguageKind OldLanguage = Style.Language;
+ FormatStyle::LanguageKind Language =
+ ((FormatStyle *)IO.getContext())->Language;
+ if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
+ IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
+ return;
+ }
+ Style.Language = OldLanguage;
+ }
+ }
+
+ // Initialize some variables used in the parsing. The using logic is at the
+ // end.
+
+ // For backward compatibility:
+ // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
+ // false unless BasedOnStyle was Google or Chromium whereas that of
+ // AllowAllConstructorInitializersOnNextLine was always true, so the
+ // equivalent default value of PackConstructorInitializers is PCIS_NextLine
+ // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
+ // had a non-default value while PackConstructorInitializers has a default
+ // value, set the latter to an equivalent non-default value if needed.
+ const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive("google") ||
+ BasedOnStyle.equals_insensitive("chromium");
+ bool OnCurrentLine = IsGoogleOrChromium;
+ bool OnNextLine = true;
+
+ bool BreakBeforeInheritanceComma = false;
+ bool BreakConstructorInitializersBeforeComma = false;
+
+ bool DeriveLineEnding = true;
+ bool UseCRLF = false;
+
+ bool SpaceInEmptyBlock = false;
+ bool SpaceInEmptyParentheses = false;
+ bool SpacesInConditionalStatement = false;
+ bool SpacesInCStyleCastParentheses = false;
+ bool SpacesInParentheses = false;
+
+ if (IO.outputting()) {
+ IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
+ } else {
+ // For backward compatibility.
+ BracketAlignmentStyle LocalBAS = BAS_Align;
+ if (IsGoogleOrChromium) {
+ FormatStyle::LanguageKind Language = Style.Language;
+ if (Language == FormatStyle::LK_None)
+ Language = ((FormatStyle *)IO.getContext())->Language;
+ if (Language == FormatStyle::LK_JavaScript)
+ LocalBAS = BAS_AlwaysBreak;
+ else if (Language == FormatStyle::LK_Java)
+ LocalBAS = BAS_DontAlign;
+ } else if (BasedOnStyle.equals_insensitive("webkit")) {
+ LocalBAS = BAS_DontAlign;
+ }
+ IO.mapOptional("AlignAfterOpenBracket", LocalBAS);
+ Style.BreakAfterOpenBracketBracedList = false;
+ Style.BreakAfterOpenBracketFunction = false;
+ Style.BreakAfterOpenBracketIf = false;
+ Style.BreakAfterOpenBracketLoop = false;
+ Style.BreakAfterOpenBracketSwitch = false;
+ Style.BreakBeforeCloseBracketBracedList = false;
+ Style.BreakBeforeCloseBracketFunction = false;
+ Style.BreakBeforeCloseBracketIf = false;
+ Style.BreakBeforeCloseBracketLoop = false;
+ Style.BreakBeforeCloseBracketSwitch = false;
+
+ switch (LocalBAS) {
+ case BAS_DontAlign:
+ Style.AlignAfterOpenBracket = false;
+ break;
+ case BAS_BlockIndent:
+ Style.BreakBeforeCloseBracketBracedList = true;
+ Style.BreakBeforeCloseBracketFunction = true;
+ Style.BreakBeforeCloseBracketIf = true;
+ [[fallthrough]];
+ case BAS_AlwaysBreak:
+ Style.BreakAfterOpenBracketBracedList = true;
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BreakAfterOpenBracketIf = true;
+ [[fallthrough]];
+ case BAS_Align:
+ Style.AlignAfterOpenBracket = true;
+ break;
+ }
+ }
+
+ // For backward compatibility.
+ if (!IO.outputting()) {
+ IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
+ IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
+ IO.mapOptional("AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
+ IO.mapOptional("AlwaysBreakTemplateDeclarations",
+ Style.BreakTemplateDeclarations);
+ IO.mapOptional("BreakBeforeInheritanceComma",
+ BreakBeforeInheritanceComma);
+ IO.mapOptional("BreakConstructorInitializersBeforeComma",
+ BreakConstructorInitializersBeforeComma);
+ IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
+ OnCurrentLine);
+ IO.mapOptional("DeriveLineEnding", DeriveLineEnding);
+ IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
+ IO.mapOptional("KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
+ IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
+ Style.KeepEmptyLines.AtStartOfBlock);
+ IO.mapOptional("IndentFunctionDeclarationAfterType",
+ Style.IndentWrappedFunctionNames);
+ IO.mapOptional("IndentRequires", Style.IndentRequiresClause);
+ IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
+ IO.mapOptional("SpaceAfterCompoundLiteralType",
+ Style.SpaceAfterCompoundLiteralType);
+ IO.mapOptional("SpaceAfterControlStatementKeyword",
+ Style.SpaceBeforeParens);
+ IO.mapOptional("SpaceInEmptyBlock", SpaceInEmptyBlock);
+ IO.mapOptional("SpaceInEmptyParentheses", SpaceInEmptyParentheses);
+ IO.mapOptional("SpacesInConditionalStatement",
+ SpacesInConditionalStatement);
+ IO.mapOptional("SpacesInCStyleCastParentheses",
+ SpacesInCStyleCastParentheses);
+ IO.mapOptional("SpacesInParentheses", SpacesInParentheses);
+ IO.mapOptional("UseCRLF", UseCRLF);
+ }
+
+ IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
+ IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
+ IO.mapOptional("AlignConsecutiveAssignments",
+ Style.AlignConsecutiveAssignments);
+ IO.mapOptional("AlignConsecutiveBitFields",
+ Style.AlignConsecutiveBitFields);
+ IO.mapOptional("AlignConsecutiveDeclarations",
+ Style.AlignConsecutiveDeclarations);
+ IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
+ IO.mapOptional("AlignConsecutiveShortCaseStatements",
+ Style.AlignConsecutiveShortCaseStatements);
+ IO.mapOptional("AlignConsecutiveTableGenBreakingDAGArgColons",
+ Style.AlignConsecutiveTableGenBreakingDAGArgColons);
+ IO.mapOptional("AlignConsecutiveTableGenCondOperatorColons",
+ Style.AlignConsecutiveTableGenCondOperatorColons);
+ IO.mapOptional("AlignConsecutiveTableGenDefinitionColons",
+ Style.AlignConsecutiveTableGenDefinitionColons);
+ IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
+ IO.mapOptional("AlignOperands", Style.AlignOperands);
+ IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
+ IO.mapOptional("AllowAllArgumentsOnNextLine",
+ Style.AllowAllArgumentsOnNextLine);
+ IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
+ Style.AllowAllParametersOfDeclarationOnNextLine);
+ IO.mapOptional("AllowBreakBeforeNoexceptSpecifier",
+ Style.AllowBreakBeforeNoexceptSpecifier);
+ IO.mapOptional("AllowBreakBeforeQtProperty",
+ Style.AllowBreakBeforeQtProperty);
+ IO.mapOptional("AllowShortBlocksOnASingleLine",
+ Style.AllowShortBlocksOnASingleLine);
+ IO.mapOptional("AllowShortCaseExpressionOnASingleLine",
+ Style.AllowShortCaseExpressionOnASingleLine);
+ IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
+ Style.AllowShortCaseLabelsOnASingleLine);
+ IO.mapOptional("AllowShortCompoundRequirementOnASingleLine",
+ Style.AllowShortCompoundRequirementOnASingleLine);
+ IO.mapOptional("AllowShortEnumsOnASingleLine",
+ Style.AllowShortEnumsOnASingleLine);
+ IO.mapOptional("AllowShortFunctionsOnASingleLine",
+ Style.AllowShortFunctionsOnASingleLine);
+ IO.mapOptional("AllowShortIfStatementsOnASingleLine",
+ Style.AllowShortIfStatementsOnASingleLine);
+ IO.mapOptional("AllowShortLambdasOnASingleLine",
+ Style.AllowShortLambdasOnASingleLine);
+ IO.mapOptional("AllowShortLoopsOnASingleLine",
+ Style.AllowShortLoopsOnASingleLine);
+ IO.mapOptional("AllowShortNamespacesOnASingleLine",
+ Style.AllowShortNamespacesOnASingleLine);
+ IO.mapOptional("AllowShortRecordOnASingleLine",
+ Style.AllowShortRecordOnASingleLine);
+ IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
+ Style.AlwaysBreakAfterDefinitionReturnType);
+ IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
+ Style.AlwaysBreakBeforeMultilineStrings);
+ IO.mapOptional("AttributeMacros", Style.AttributeMacros);
+ IO.mapOptional("BinPackArguments", Style.BinPackArguments);
+ IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList);
+ IO.mapOptional("BinPackParameters", Style.BinPackParameters);
+ IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
+ IO.mapOptional("BracedInitializerIndentWidth",
+ Style.BracedInitializerIndentWidth);
+ IO.mapOptional("BraceWrapping", Style.BraceWrapping);
+ IO.mapOptional("BreakAdjacentStringLiterals",
+ Style.BreakAdjacentStringLiterals);
+ IO.mapOptional("BreakAfterAttributes", Style.BreakAfterAttributes);
+ IO.mapOptional("BreakAfterJavaFieldAnnotations",
+ Style.BreakAfterJavaFieldAnnotations);
+ IO.mapOptional("BreakAfterOpenBracketBracedList",
+ Style.BreakAfterOpenBracketBracedList);
+ IO.mapOptional("BreakAfterOpenBracketFunction",
+ Style.BreakAfterOpenBracketFunction);
+ IO.mapOptional("BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
+ IO.mapOptional("BreakAfterOpenBracketLoop",
+ Style.BreakAfterOpenBracketLoop);
+ IO.mapOptional("BreakAfterOpenBracketSwitch",
+ Style.BreakAfterOpenBracketSwitch);
+ IO.mapOptional("BreakAfterReturnType", Style.BreakAfterReturnType);
+ IO.mapOptional("BreakArrays", Style.BreakArrays);
+ IO.mapOptional("BreakBeforeBinaryOperators",
+ Style.BreakBeforeBinaryOperators);
+ IO.mapOptional("BreakBeforeCloseBracketBracedList",
+ Style.BreakBeforeCloseBracketBracedList);
+ IO.mapOptional("BreakBeforeCloseBracketFunction",
+ Style.BreakBeforeCloseBracketFunction);
+ IO.mapOptional("BreakBeforeCloseBracketIf",
+ Style.BreakBeforeCloseBracketIf);
+ IO.mapOptional("BreakBeforeCloseBracketLoop",
+ Style.BreakBeforeCloseBracketLoop);
+ IO.mapOptional("BreakBeforeCloseBracketSwitch",
+ Style.BreakBeforeCloseBracketSwitch);
+ IO.mapOptional("BreakBeforeConceptDeclarations",
+ Style.BreakBeforeConceptDeclarations);
+ IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
+ IO.mapOptional("BreakBeforeInlineASMColon",
+ Style.BreakBeforeInlineASMColon);
+ IO.mapOptional("BreakBeforeTemplateCloser",
+ Style.BreakBeforeTemplateCloser);
+ IO.mapOptional("BreakBeforeTernaryOperators",
+ Style.BreakBeforeTernaryOperators);
+ IO.mapOptional("BreakBinaryOperations", Style.BreakBinaryOperations);
+ IO.mapOptional("BreakConstructorInitializers",
+ Style.BreakConstructorInitializers);
+ IO.mapOptional("BreakFunctionDefinitionParameters",
+ Style.BreakFunctionDefinitionParameters);
+ IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
+ IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
+ IO.mapOptional("BreakTemplateDeclarations",
+ Style.BreakTemplateDeclarations);
+ IO.mapOptional("ColumnLimit", Style.ColumnLimit);
+ IO.mapOptional("CommentPragmas", Style.CommentPragmas);
+ IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
+ IO.mapOptional("ConstructorInitializerIndentWidth",
+ Style.ConstructorInitializerIndentWidth);
+ IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
+ IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
+ IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
+ IO.mapOptional("DisableFormat", Style.DisableFormat);
+ IO.mapOptional("EmptyLineAfterAccessModifier",
+ Style.EmptyLineAfterAccessModifier);
+ IO.mapOptional("EmptyLineBeforeAccessModifier",
+ Style.EmptyLineBeforeAccessModifier);
+ IO.mapOptional("EnumTrailingComma", Style.EnumTrailingComma);
+ IO.mapOptional("ExperimentalAutoDetectBinPacking",
+ Style.ExperimentalAutoDetectBinPacking);
+ IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
+ IO.mapOptional("ForEachMacros", Style.ForEachMacros);
+ IO.mapOptional("IfMacros", Style.IfMacros);
+ IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
+ IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
+ IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
+ IO.mapOptional("IncludeIsMainSourceRegex",
+ Style.IncludeStyle.IncludeIsMainSourceRegex);
+ IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
+ IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
+ IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
+ IO.mapOptional("IndentExportBlock", Style.IndentExportBlock);
+ IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
+ IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
+ IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
+ IO.mapOptional("IndentRequiresClause", Style.IndentRequiresClause);
+ IO.mapOptional("IndentWidth", Style.IndentWidth);
+ IO.mapOptional("IndentWrappedFunctionNames",
+ Style.IndentWrappedFunctionNames);
+ IO.mapOptional("InsertBraces", Style.InsertBraces);
+ IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
+ IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
+ IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
+ IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
+ IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
+ IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
+ IO.mapOptional("KeepEmptyLines", Style.KeepEmptyLines);
+ IO.mapOptional("KeepFormFeed", Style.KeepFormFeed);
+ IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
+ IO.mapOptional("LineEnding", Style.LineEnding);
+ IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
+ IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
+ IO.mapOptional("Macros", Style.Macros);
+ IO.mapOptional("MacrosSkippedByRemoveParentheses",
+ Style.MacrosSkippedByRemoveParentheses);
+ IO.mapOptional("MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
+ IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
+ IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
+ IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
+ IO.mapOptional("NumericLiteralCase", Style.NumericLiteralCase);
+ IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
+ IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
+ IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
+ Style.ObjCBreakBeforeNestedBlockParam);
+ IO.mapOptional("ObjCPropertyAttributeOrder",
+ Style.ObjCPropertyAttributeOrder);
+ IO.mapOptional("ObjCSpaceAfterMethodDeclarationPrefix",
+ Style.ObjCSpaceAfterMethodDeclarationPrefix);
+ IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
+ IO.mapOptional("ObjCSpaceBeforeProtocolList",
+ Style.ObjCSpaceBeforeProtocolList);
+ IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
+ IO.mapOptional("PackConstructorInitializers",
+ Style.PackConstructorInitializers);
+ IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
+ IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
+ Style.PenaltyBreakBeforeFirstCallParameter);
+ IO.mapOptional("PenaltyBreakBeforeMemberAccess",
+ Style.PenaltyBreakBeforeMemberAccess);
+ IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
+ IO.mapOptional("PenaltyBreakFirstLessLess",
+ Style.PenaltyBreakFirstLessLess);
+ IO.mapOptional("PenaltyBreakOpenParenthesis",
+ Style.PenaltyBreakOpenParenthesis);
+ IO.mapOptional("PenaltyBreakScopeResolution",
+ Style.PenaltyBreakScopeResolution);
+ IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
+ IO.mapOptional("PenaltyBreakTemplateDeclaration",
+ Style.PenaltyBreakTemplateDeclaration);
+ IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
+ IO.mapOptional("PenaltyIndentedWhitespace",
+ Style.PenaltyIndentedWhitespace);
+ IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
+ Style.PenaltyReturnTypeOnItsOwnLine);
+ IO.mapOptional("PointerAlignment", Style.PointerAlignment);
+ IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
+ IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
+ // Default Order for Left/Right based Qualifier alignment.
+ if (Style.QualifierAlignment == FormatStyle::QAS_Right)
+ Style.QualifierOrder = {"type", "const", "volatile"};
+ else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
+ Style.QualifierOrder = {"const", "volatile", "type"};
+ else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
+ IO.mapOptional("QualifierOrder", Style.QualifierOrder);
+ IO.mapOptional("RawStringFormats", Style.RawStringFormats);
+ IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
+ IO.mapOptional("ReflowComments", Style.ReflowComments);
+ IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
+ IO.mapOptional("RemoveEmptyLinesInUnwrappedLines",
+ Style.RemoveEmptyLinesInUnwrappedLines);
+ IO.mapOptional("RemoveParentheses", Style.RemoveParentheses);
+ IO.mapOptional("RemoveSemicolon", Style.RemoveSemicolon);
+ IO.mapOptional("RequiresClausePosition", Style.RequiresClausePosition);
+ IO.mapOptional("RequiresExpressionIndentation",
+ Style.RequiresExpressionIndentation);
+ IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
+ IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
+ IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
+ IO.mapOptional("SortIncludes", Style.SortIncludes);
+ IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
+ IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
+ IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
+ IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
+ IO.mapOptional("SpaceAfterOperatorKeyword",
+ Style.SpaceAfterOperatorKeyword);
+ IO.mapOptional("SpaceAfterTemplateKeyword",
+ Style.SpaceAfterTemplateKeyword);
+ IO.mapOptional("SpaceAroundPointerQualifiers",
+ Style.SpaceAroundPointerQualifiers);
+ IO.mapOptional("SpaceBeforeAssignmentOperators",
+ Style.SpaceBeforeAssignmentOperators);
+ IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
+ IO.mapOptional("SpaceBeforeCpp11BracedList",
+ Style.SpaceBeforeCpp11BracedList);
+ IO.mapOptional("SpaceBeforeCtorInitializerColon",
+ Style.SpaceBeforeCtorInitializerColon);
+ IO.mapOptional("SpaceBeforeInheritanceColon",
+ Style.SpaceBeforeInheritanceColon);
+ IO.mapOptional("SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
+ IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
+ IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
+ IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
+ Style.SpaceBeforeRangeBasedForLoopColon);
+ IO.mapOptional("SpaceBeforeSquareBrackets",
+ Style.SpaceBeforeSquareBrackets);
+ IO.mapOptional("SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
+ IO.mapOptional("SpacesBeforeTrailingComments",
+ Style.SpacesBeforeTrailingComments);
+ IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
+ IO.mapOptional("SpacesInContainerLiterals",
+ Style.SpacesInContainerLiterals);
+ IO.mapOptional("SpacesInLineCommentPrefix",
+ Style.SpacesInLineCommentPrefix);
+ IO.mapOptional("SpacesInParens", Style.SpacesInParens);
+ IO.mapOptional("SpacesInParensOptions", Style.SpacesInParensOptions);
+ IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
+ IO.mapOptional("Standard", Style.Standard);
+ IO.mapOptional("StatementAttributeLikeMacros",
+ Style.StatementAttributeLikeMacros);
+ IO.mapOptional("StatementMacros", Style.StatementMacros);
+ IO.mapOptional("TableGenBreakingDAGArgOperators",
+ Style.TableGenBreakingDAGArgOperators);
+ IO.mapOptional("TableGenBreakInsideDAGArg",
+ Style.TableGenBreakInsideDAGArg);
+ IO.mapOptional("TabWidth", Style.TabWidth);
+ IO.mapOptional("TemplateNames", Style.TemplateNames);
+ IO.mapOptional("TypeNames", Style.TypeNames);
+ IO.mapOptional("TypenameMacros", Style.TypenameMacros);
+ IO.mapOptional("UseTab", Style.UseTab);
+ IO.mapOptional("VariableTemplates", Style.VariableTemplates);
+ IO.mapOptional("VerilogBreakBetweenInstancePorts",
+ Style.VerilogBreakBetweenInstancePorts);
+ IO.mapOptional("WhitespaceSensitiveMacros",
+ Style.WhitespaceSensitiveMacros);
+ IO.mapOptional("WrapNamespaceBodyWithEmptyLines",
+ Style.WrapNamespaceBodyWithEmptyLines);
+
+ // If AlwaysBreakAfterDefinitionReturnType was specified but
+ // BreakAfterReturnType was not, initialize the latter from the former for
+ // backwards compatibility.
+ if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
+ Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
+ if (Style.AlwaysBreakAfterDefinitionReturnType ==
+ FormatStyle::DRTBS_All) {
+ Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
+ } else if (Style.AlwaysBreakAfterDefinitionReturnType ==
+ FormatStyle::DRTBS_TopLevel) {
+ Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
+ }
+ }
+
+ // If BreakBeforeInheritanceComma was specified but BreakInheritance was
+ // not, initialize the latter from the former for backwards compatibility.
+ if (BreakBeforeInheritanceComma &&
+ Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
+ Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+ }
+
+ // If BreakConstructorInitializersBeforeComma was specified but
+ // BreakConstructorInitializers was not, initialize the latter from the
+ // former for backwards compatibility.
+ if (BreakConstructorInitializersBeforeComma &&
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ }
+
+ if (!IsGoogleOrChromium) {
+ if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
+ OnCurrentLine) {
+ Style.PackConstructorInitializers = OnNextLine
+ ? FormatStyle::PCIS_NextLine
+ : FormatStyle::PCIS_CurrentLine;
+ }
+ } else if (Style.PackConstructorInitializers ==
+ FormatStyle::PCIS_NextLine) {
+ if (!OnCurrentLine)
+ Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
+ else if (!OnNextLine)
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ }
+
+ if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
+ if (!DeriveLineEnding)
+ Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
+ else if (UseCRLF)
+ Style.LineEnding = FormatStyle::LE_DeriveCRLF;
+ }
+
+ // If SpaceInEmptyBlock was specified but SpaceInEmptyBraces was not,
+ // initialize the latter from the former for backward compatibility.
+ if (SpaceInEmptyBlock &&
+ Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
+ Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
+ }
+
+ if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
+ (SpacesInParentheses || SpaceInEmptyParentheses ||
+ SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
+ if (SpacesInParentheses) {
+ // For backward compatibility.
+ Style.SpacesInParensOptions.ExceptDoubleParentheses = false;
+ Style.SpacesInParensOptions.InConditionalStatements = true;
+ Style.SpacesInParensOptions.InCStyleCasts =
+ SpacesInCStyleCastParentheses;
+ Style.SpacesInParensOptions.InEmptyParentheses =
+ SpaceInEmptyParentheses;
+ Style.SpacesInParensOptions.Other = true;
+ } else {
+ Style.SpacesInParensOptions = {};
+ Style.SpacesInParensOptions.InConditionalStatements =
+ SpacesInConditionalStatement;
+ Style.SpacesInParensOptions.InCStyleCasts =
+ SpacesInCStyleCastParentheses;
+ Style.SpacesInParensOptions.InEmptyParentheses =
+ SpaceInEmptyParentheses;
+ }
+ Style.SpacesInParens = FormatStyle::SIPO_Custom;
+ }
+ }
+};
+
+// Allows to read vector<FormatStyle> while keeping default values.
+// IO.getContext() should contain a pointer to the FormatStyle structure, that
+// will be used to get default values for missing keys.
+// If the first element has no Language specified, it will be treated as the
+// default one for the following elements.
+template <> struct DocumentListTraits<std::vector<FormatStyle>> {
+ static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
+ return Seq.size();
+ }
+ static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
+ size_t Index) {
+ if (Index >= Seq.size()) {
+ assert(Index == Seq.size());
+ FormatStyle Template;
+ if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
+ Template = Seq[0];
+ } else {
+ Template = *((const FormatStyle *)IO.getContext());
+ Template.Language = FormatStyle::LK_None;
+ }
+ Seq.resize(Index + 1, Template);
+ }
+ return Seq[Index];
+ }
+};
+
+template <> struct ScalarEnumerationTraits<FormatStyle::IndentGotoLabelStyle> {
+ static void enumeration(IO &IO, FormatStyle::IndentGotoLabelStyle &Value) {
+ IO.enumCase(Value, "NoIndent", FormatStyle::IGLS_NoIndent);
+ IO.enumCase(Value, "OuterIndent", FormatStyle::IGLS_OuterIndent);
+ IO.enumCase(Value, "InnerIndent", FormatStyle::IGLS_InnerIndent);
+ IO.enumCase(Value, "HalfIndent", FormatStyle::IGLS_HalfIndent);
+
+ // For backward compatibility.
+ IO.enumCase(Value, "false", FormatStyle::IGLS_NoIndent);
+ IO.enumCase(Value, "true", FormatStyle::IGLS_OuterIndent);
+ }
+};
+
+} // namespace yaml
+} // namespace llvm
+
+namespace clang {
+namespace format {
+
+const std::error_category &getParseCategory() {
+ static const ParseErrorCategory C{};
+ return C;
+}
+std::error_code make_error_code(ParseError e) {
+ return std::error_code(static_cast<int>(e), getParseCategory());
+}
+
+inline llvm::Error make_string_error(const Twine &Message) {
+ return llvm::make_error<llvm::StringError>(Message,
+ llvm::inconvertibleErrorCode());
+}
+
+const char *ParseErrorCategory::name() const noexcept {
+ return "clang-format.parse_error";
+}
+
+std::string ParseErrorCategory::message(int EV) const {
+ switch (static_cast<ParseError>(EV)) {
+ case ParseError::Success:
+ return "Success";
+ case ParseError::Error:
+ return "Invalid argument";
+ case ParseError::Unsuitable:
+ return "Unsuitable";
+ case ParseError::BinPackTrailingCommaConflict:
+ return "trailing comma insertion cannot be used with bin packing";
+ case ParseError::InvalidQualifierSpecified:
+ return "Invalid qualifier specified in QualifierOrder";
+ case ParseError::DuplicateQualifierSpecified:
+ return "Duplicate qualifier specified in QualifierOrder";
+ case ParseError::MissingQualifierType:
+ return "Missing type in QualifierOrder";
+ case ParseError::MissingQualifierOrder:
+ return "Missing QualifierOrder";
+ }
+ llvm_unreachable("unexpected parse error");
+}
+
+static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
+ if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
+ return;
+ Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
+ /*AfterClass=*/false,
+ /*AfterControlStatement=*/FormatStyle::BWACS_Never,
+ /*AfterEnum=*/false,
+ /*AfterFunction=*/false,
+ /*AfterNamespace=*/false,
+ /*AfterObjCDeclaration=*/false,
+ /*AfterStruct=*/false,
+ /*AfterUnion=*/false,
+ /*AfterExternBlock=*/false,
+ /*BeforeCatch=*/false,
+ /*BeforeElse=*/false,
+ /*BeforeLambdaBody=*/false,
+ /*BeforeWhile=*/false,
+ /*IndentBraces=*/false,
+ /*SplitEmptyFunction=*/true,
+ /*SplitEmptyRecord=*/true,
+ /*SplitEmptyNamespace=*/true};
+ switch (Expanded.BreakBeforeBraces) {
+ case FormatStyle::BS_Linux:
+ Expanded.BraceWrapping.AfterClass = true;
+ Expanded.BraceWrapping.AfterFunction = true;
+ Expanded.BraceWrapping.AfterNamespace = true;
+ break;
+ case FormatStyle::BS_Mozilla:
+ Expanded.BraceWrapping.AfterClass = true;
+ Expanded.BraceWrapping.AfterEnum = true;
+ Expanded.BraceWrapping.AfterFunction = true;
+ Expanded.BraceWrapping.AfterStruct = true;
+ Expanded.BraceWrapping.AfterUnion = true;
+ Expanded.BraceWrapping.AfterExternBlock = true;
+ Expanded.BraceWrapping.SplitEmptyFunction = true;
+ Expanded.BraceWrapping.SplitEmptyRecord = false;
+ break;
+ case FormatStyle::BS_Stroustrup:
+ Expanded.BraceWrapping.AfterFunction = true;
+ Expanded.BraceWrapping.BeforeCatch = true;
+ Expanded.BraceWrapping.BeforeElse = true;
+ break;
+ case FormatStyle::BS_Allman:
+ Expanded.BraceWrapping.AfterCaseLabel = true;
+ Expanded.BraceWrapping.AfterClass = true;
+ Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ Expanded.BraceWrapping.AfterEnum = true;
+ Expanded.BraceWrapping.AfterFunction = true;
+ Expanded.BraceWrapping.AfterNamespace = true;
+ Expanded.BraceWrapping.AfterObjCDeclaration = true;
+ Expanded.BraceWrapping.AfterStruct = true;
+ Expanded.BraceWrapping.AfterUnion = true;
+ Expanded.BraceWrapping.AfterExternBlock = true;
+ Expanded.BraceWrapping.BeforeCatch = true;
+ Expanded.BraceWrapping.BeforeElse = true;
+ Expanded.BraceWrapping.BeforeLambdaBody = true;
+ break;
+ case FormatStyle::BS_Whitesmiths:
+ Expanded.BraceWrapping.AfterCaseLabel = true;
+ Expanded.BraceWrapping.AfterClass = true;
+ Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ Expanded.BraceWrapping.AfterEnum = true;
+ Expanded.BraceWrapping.AfterFunction = true;
+ Expanded.BraceWrapping.AfterNamespace = true;
+ Expanded.BraceWrapping.AfterObjCDeclaration = true;
+ Expanded.BraceWrapping.AfterStruct = true;
+ Expanded.BraceWrapping.AfterExternBlock = true;
+ Expanded.BraceWrapping.BeforeCatch = true;
+ Expanded.BraceWrapping.BeforeElse = true;
+ Expanded.BraceWrapping.BeforeLambdaBody = true;
+ break;
+ case FormatStyle::BS_GNU:
+ Expanded.BraceWrapping = {
+ /*AfterCaseLabel=*/true,
+ /*AfterClass=*/true,
+ /*AfterControlStatement=*/FormatStyle::BWACS_Always,
+ /*AfterEnum=*/true,
+ /*AfterFunction=*/true,
+ /*AfterNamespace=*/true,
+ /*AfterObjCDeclaration=*/true,
+ /*AfterStruct=*/true,
+ /*AfterUnion=*/true,
+ /*AfterExternBlock=*/true,
+ /*BeforeCatch=*/true,
+ /*BeforeElse=*/true,
+ /*BeforeLambdaBody=*/true,
+ /*BeforeWhile=*/true,
+ /*IndentBraces=*/true,
+ /*SplitEmptyFunction=*/true,
+ /*SplitEmptyRecord=*/true,
+ /*SplitEmptyNamespace=*/true};
+ break;
+ case FormatStyle::BS_WebKit:
+ Expanded.BraceWrapping.AfterFunction = true;
+ break;
+ default:
+ break;
+ }
+}
+
+static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded) {
+ if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
+ return;
+ // Reset all flags
+ Expanded.SpaceBeforeParensOptions = {};
+ Expanded.SpaceBeforeParensOptions.AfterPlacementOperator = true;
+
+ switch (Expanded.SpaceBeforeParens) {
+ case FormatStyle::SBPO_ControlStatements:
+ Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
+ Expanded.SpaceBeforeParensOptions.AfterForeachMacros = true;
+ Expanded.SpaceBeforeParensOptions.AfterIfMacros = true;
+ break;
+ case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
+ Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
+ break;
+ case FormatStyle::SBPO_NonEmptyParentheses:
+ Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
+ break;
+ default:
+ break;
+ }
+}
+
+static void expandPresetsSpacesInParens(FormatStyle &Expanded) {
+ if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
+ return;
+ assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
+ // Reset all flags
+ Expanded.SpacesInParensOptions = {};
+}
+
+FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
+ FormatStyle LLVMStyle;
+ LLVMStyle.AccessModifierOffset = -2;
+ LLVMStyle.AlignAfterOpenBracket = true;
+ LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
+ LLVMStyle.AlignConsecutiveAssignments = {};
+ LLVMStyle.AlignConsecutiveAssignments.PadOperators = true;
+ LLVMStyle.AlignConsecutiveBitFields = {};
+ LLVMStyle.AlignConsecutiveDeclarations = {};
+ LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations = true;
+ LLVMStyle.AlignConsecutiveMacros = {};
+ LLVMStyle.AlignConsecutiveShortCaseStatements = {};
+ LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
+ LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
+ LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
+ LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
+ LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
+ LLVMStyle.AlignTrailingComments = {};
+ LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
+ LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
+ LLVMStyle.AlignTrailingComments.AlignPPAndNotPP = true;
+ LLVMStyle.AllowAllArgumentsOnNextLine = true;
+ LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
+ LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
+ LLVMStyle.AllowBreakBeforeQtProperty = false;
+ LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+ LLVMStyle.AllowShortCaseExpressionOnASingleLine = true;
+ LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
+ LLVMStyle.AllowShortCompoundRequirementOnASingleLine = true;
+ LLVMStyle.AllowShortEnumsOnASingleLine = true;
+ LLVMStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
+ LLVMStyle.AllowShortLoopsOnASingleLine = false;
+ LLVMStyle.AllowShortNamespacesOnASingleLine = false;
+ LLVMStyle.AllowShortRecordOnASingleLine = FormatStyle::SRS_EmptyAndAttached;
+ LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
+ LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
+ LLVMStyle.AttributeMacros.push_back("__capability");
+ LLVMStyle.BinPackArguments = true;
+ LLVMStyle.BinPackLongBracedList = true;
+ LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
+ LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
+ LLVMStyle.BracedInitializerIndentWidth = -1;
+ LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
+ /*AfterClass=*/false,
+ /*AfterControlStatement=*/FormatStyle::BWACS_Never,
+ /*AfterEnum=*/false,
+ /*AfterFunction=*/false,
+ /*AfterNamespace=*/false,
+ /*AfterObjCDeclaration=*/false,
+ /*AfterStruct=*/false,
+ /*AfterUnion=*/false,
+ /*AfterExternBlock=*/false,
+ /*BeforeCatch=*/false,
+ /*BeforeElse=*/false,
+ /*BeforeLambdaBody=*/false,
+ /*BeforeWhile=*/false,
+ /*IndentBraces=*/false,
+ /*SplitEmptyFunction=*/true,
+ /*SplitEmptyRecord=*/true,
+ /*SplitEmptyNamespace=*/true};
+ LLVMStyle.BreakAdjacentStringLiterals = true;
+ LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
+ LLVMStyle.BreakAfterJavaFieldAnnotations = false;
+ LLVMStyle.BreakAfterOpenBracketBracedList = false;
+ LLVMStyle.BreakAfterOpenBracketFunction = false;
+ LLVMStyle.BreakAfterOpenBracketIf = false;
+ LLVMStyle.BreakAfterOpenBracketLoop = false;
+ LLVMStyle.BreakAfterOpenBracketSwitch = false;
+ LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
+ LLVMStyle.BreakArrays = true;
+ LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+ LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
+ LLVMStyle.BreakBeforeCloseBracketBracedList = false;
+ LLVMStyle.BreakBeforeCloseBracketFunction = false;
+ LLVMStyle.BreakBeforeCloseBracketIf = false;
+ LLVMStyle.BreakBeforeCloseBracketLoop = false;
+ LLVMStyle.BreakBeforeCloseBracketSwitch = false;
+ LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
+ LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
+ LLVMStyle.BreakBeforeTemplateCloser = false;
+ LLVMStyle.BreakBeforeTernaryOperators = true;
+ LLVMStyle.BreakBinaryOperations = {FormatStyle::BBO_Never, {}};
+ LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
+ LLVMStyle.BreakFunctionDefinitionParameters = false;
+ LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
+ LLVMStyle.BreakStringLiterals = true;
+ LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
+ LLVMStyle.ColumnLimit = 80;
+ LLVMStyle.CommentPragmas = "^ IWYU pragma:";
+ LLVMStyle.CompactNamespaces = false;
+ LLVMStyle.ConstructorInitializerIndentWidth = 4;
+ LLVMStyle.ContinuationIndentWidth = 4;
+ LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
+ LLVMStyle.DerivePointerAlignment = false;
+ LLVMStyle.DisableFormat = false;
+ LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
+ LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
+ LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
+ LLVMStyle.ExperimentalAutoDetectBinPacking = false;
+ LLVMStyle.FixNamespaceComments = true;
+ LLVMStyle.ForEachMacros.push_back("foreach");
+ LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
+ LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
+ LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
+ LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
+ LLVMStyle.IncludeStyle.IncludeCategories = {
+ {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
+ {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
+ {".*", 1, 0, false}};
+ LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
+ LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
+ LLVMStyle.IndentAccessModifiers = false;
+ LLVMStyle.IndentCaseBlocks = false;
+ LLVMStyle.IndentCaseLabels = false;
+ LLVMStyle.IndentExportBlock = true;
+ LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+ LLVMStyle.IndentGotoLabels = FormatStyle::IGLS_OuterIndent;
+ LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
+ LLVMStyle.IndentRequiresClause = true;
+ LLVMStyle.IndentWidth = 2;
+ LLVMStyle.IndentWrappedFunctionNames = false;
+ LLVMStyle.InsertBraces = false;
+ LLVMStyle.InsertNewlineAtEOF = false;
+ LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
+ LLVMStyle.IntegerLiteralSeparator = {};
+ LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
+ LLVMStyle.JavaScriptWrapImports = true;
+ LLVMStyle.KeepEmptyLines = {
+ /*AtEndOfFile=*/false,
+ /*AtStartOfBlock=*/true,
+ /*AtStartOfFile=*/true,
+ };
+ LLVMStyle.KeepFormFeed = false;
+ LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
+ LLVMStyle.Language = Language;
+ LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
+ LLVMStyle.MaxEmptyLinesToKeep = 1;
+ LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
+ LLVMStyle.NumericLiteralCase = {/*ExponentLetter=*/FormatStyle::NLCS_Leave,
+ /*HexDigit=*/FormatStyle::NLCS_Leave,
+ /*Prefix=*/FormatStyle::NLCS_Leave,
+ /*Suffix=*/FormatStyle::NLCS_Leave};
+ LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
+ LLVMStyle.ObjCBlockIndentWidth = 2;
+ LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
+ LLVMStyle.ObjCSpaceAfterMethodDeclarationPrefix = true;
+ LLVMStyle.ObjCSpaceAfterProperty = false;
+ LLVMStyle.ObjCSpaceBeforeProtocolList = true;
+ LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
+ LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
+ LLVMStyle.PPIndentWidth = -1;
+ LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
+ LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
+ LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
+ LLVMStyle.RemoveBracesLLVM = false;
+ LLVMStyle.RemoveEmptyLinesInUnwrappedLines = false;
+ LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
+ LLVMStyle.RemoveSemicolon = false;
+ LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
+ LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
+ LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
+ LLVMStyle.ShortNamespaceLines = 1;
+ LLVMStyle.SkipMacroDefinitionBody = false;
+ LLVMStyle.SortIncludes = {/*Enabled=*/true, /*IgnoreCase=*/false,
+ /*IgnoreExtension=*/false};
+ LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
+ LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
+ LLVMStyle.SpaceAfterCompoundLiteralType = false;
+ LLVMStyle.SpaceAfterCStyleCast = false;
+ LLVMStyle.SpaceAfterLogicalNot = false;
+ LLVMStyle.SpaceAfterOperatorKeyword = false;
+ LLVMStyle.SpaceAfterTemplateKeyword = true;
+ LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
+ LLVMStyle.SpaceBeforeAssignmentOperators = true;
+ LLVMStyle.SpaceBeforeCaseColon = false;
+ LLVMStyle.SpaceBeforeCpp11BracedList = false;
+ LLVMStyle.SpaceBeforeCtorInitializerColon = true;
+ LLVMStyle.SpaceBeforeInheritanceColon = true;
+ LLVMStyle.SpaceBeforeJsonColon = false;
+ LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
+ LLVMStyle.SpaceBeforeParensOptions = {};
+ LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements = true;
+ LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros = true;
+ LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
+ LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
+ LLVMStyle.SpaceBeforeSquareBrackets = false;
+ LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
+ LLVMStyle.SpacesBeforeTrailingComments = 1;
+ LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
+ LLVMStyle.SpacesInContainerLiterals = true;
+ LLVMStyle.SpacesInLineCommentPrefix = {
+ /*Minimum=*/1, /*Maximum=*/std::numeric_limits<unsigned>::max()};
+ LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
+ LLVMStyle.SpacesInSquareBrackets = false;
+ LLVMStyle.Standard = FormatStyle::LS_Latest;
+ LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
+ LLVMStyle.StatementMacros.push_back("Q_UNUSED");
+ LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
+ LLVMStyle.TableGenBreakingDAGArgOperators = {};
+ LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
+ LLVMStyle.TabWidth = 8;
+ LLVMStyle.UseTab = FormatStyle::UT_Never;
+ LLVMStyle.VerilogBreakBetweenInstancePorts = true;
+ LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
+ LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
+ LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
+ LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
+ LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
+ LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
+
+ LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
+ LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
+ LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
+ LLVMStyle.PenaltyBreakComment = 300;
+ LLVMStyle.PenaltyBreakFirstLessLess = 120;
+ LLVMStyle.PenaltyBreakOpenParenthesis = 0;
+ LLVMStyle.PenaltyBreakScopeResolution = 500;
+ LLVMStyle.PenaltyBreakString = 1000;
+ LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
+ LLVMStyle.PenaltyExcessCharacter = 1'000'000;
+ LLVMStyle.PenaltyIndentedWhitespace = 0;
+ LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
+
+ // Defaults that differ when not C++.
+ switch (Language) {
+ case FormatStyle::LK_TableGen:
+ LLVMStyle.SpacesInContainerLiterals = false;
+ break;
+ case FormatStyle::LK_Json:
+ LLVMStyle.ColumnLimit = 0;
+ break;
+ case FormatStyle::LK_Verilog:
+ LLVMStyle.IndentCaseLabels = true;
+ LLVMStyle.SpacesInContainerLiterals = false;
+ break;
+ default:
+ break;
+ }
+
+ return LLVMStyle;
+}
+
+FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
+ if (Language == FormatStyle::LK_TextProto) {
+ FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
+ GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+ return GoogleStyle;
+ }
+
+ FormatStyle GoogleStyle = getLLVMStyle(Language);
+
+ GoogleStyle.AccessModifierOffset = -1;
+ GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ GoogleStyle.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ GoogleStyle.AllowShortLoopsOnASingleLine = true;
+ GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
+ // Abseil aliases to clang's `_Nonnull`, `_Nullable` and `_Null_unspecified`.
+ GoogleStyle.AttributeMacros.push_back("absl_nonnull");
+ GoogleStyle.AttributeMacros.push_back("absl_nullable");
+ GoogleStyle.AttributeMacros.push_back("absl_nullability_unknown");
+ GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+ GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
+ GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
+ {"^<.*\\.h>", 1, 0, false},
+ {"^<.*", 2, 0, false},
+ {".*", 3, 0, false}};
+ GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
+ GoogleStyle.IndentCaseLabels = true;
+ GoogleStyle.KeepEmptyLines.AtStartOfBlock = false;
+ GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
+ GoogleStyle.ObjCSpaceAfterProperty = false;
+ GoogleStyle.ObjCSpaceBeforeProtocolList = true;
+ GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
+ GoogleStyle.RawStringFormats = {
+ {
+ FormatStyle::LK_Cpp,
+ /*Delimiters=*/
+ {
+ "cc",
+ "CC",
+ "cpp",
+ "Cpp",
+ "CPP",
+ "c++",
+ "C++",
+ },
+ /*EnclosingFunctionNames=*/
+ {},
+ /*CanonicalDelimiter=*/"",
+ /*BasedOnStyle=*/"google",
+ },
+ {
+ FormatStyle::LK_TextProto,
+ /*Delimiters=*/
+ {
+ "pb",
+ "PB",
+ "proto",
+ "PROTO",
+ },
+ /*EnclosingFunctionNames=*/
+ {
+ "EqualsProto",
+ "EquivToProto",
+ "PARSE_PARTIAL_TEXT_PROTO",
+ "PARSE_TEST_PROTO",
+ "PARSE_TEXT_PROTO",
+ "ParseTextOrDie",
+ "ParseTextProtoOrDie",
+ "ParseTestProto",
+ "ParsePartialTestProto",
+ },
+ /*CanonicalDelimiter=*/"pb",
+ /*BasedOnStyle=*/"google",
+ },
+ };
+
+ GoogleStyle.SpacesBeforeTrailingComments = 2;
+ GoogleStyle.Standard = FormatStyle::LS_Auto;
+
+ GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
+ GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
+
+ if (Language == FormatStyle::LK_Java) {
+ GoogleStyle.AlignAfterOpenBracket = false;
+ GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
+ GoogleStyle.AlignTrailingComments = {};
+ GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
+ GoogleStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
+ GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ GoogleStyle.ColumnLimit = 100;
+ GoogleStyle.SpaceAfterCStyleCast = true;
+ GoogleStyle.SpacesBeforeTrailingComments = 1;
+ } else if (Language == FormatStyle::LK_JavaScript) {
+ GoogleStyle.BreakAfterOpenBracketBracedList = true;
+ GoogleStyle.BreakAfterOpenBracketFunction = true;
+ GoogleStyle.BreakAfterOpenBracketIf = true;
+ GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
+ GoogleStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ // TODO: still under discussion whether to switch to SLS_All.
+ GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
+ GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
+ GoogleStyle.BreakBeforeTernaryOperators = false;
+ // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
+ // commonly followed by overlong URLs.
+ GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
+ // TODO: enable once decided, in particular re disabling bin packing.
+ // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
+ // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
+ GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
+ GoogleStyle.JavaScriptWrapImports = false;
+ GoogleStyle.MaxEmptyLinesToKeep = 3;
+ GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
+ GoogleStyle.SpacesInContainerLiterals = false;
+ } else if (Language == FormatStyle::LK_Proto) {
+ GoogleStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
+ // This affects protocol buffer options specifications and text protos.
+ // Text protos are currently mostly formatted inside C++ raw string literals
+ // and often the current breaking behavior of string literals is not
+ // beneficial there. Investigate turning this on once proper string reflow
+ // has been implemented.
+ GoogleStyle.BreakStringLiterals = false;
+ GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
+ GoogleStyle.SpacesInContainerLiterals = false;
+ } else if (Language == FormatStyle::LK_ObjC) {
+ GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
+ GoogleStyle.ColumnLimit = 100;
+ GoogleStyle.DerivePointerAlignment = true;
+ // "Regroup" doesn't work well for ObjC yet (main header heuristic,
+ // relationship between ObjC standard library headers and other heades,
+ // #imports, etc.)
+ GoogleStyle.IncludeStyle.IncludeBlocks =
+ tooling::IncludeStyle::IBS_Preserve;
+ } else if (Language == FormatStyle::LK_CSharp) {
+ GoogleStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ GoogleStyle.BreakStringLiterals = false;
+ GoogleStyle.ColumnLimit = 100;
+ GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
+ }
+
+ return GoogleStyle;
+}
+
+FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
+ FormatStyle ChromiumStyle = getGoogleStyle(Language);
+
+ // Disable include reordering across blocks in Chromium code.
+ // - clang-format tries to detect that foo.h is the "main" header for
+ // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
+ // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
+ // _private.cc, _impl.cc etc) in different permutations
+ // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
+ // better default for Chromium code.
+ // - The default for .cc and .mm files is different (r357695) for Google style
+ // for the same reason. The plan is to unify this again once the main
+ // header detection works for Google's ObjC code, but this hasn't happened
+ // yet. Since Chromium has some ObjC code, switching Chromium is blocked
+ // on that.
+ // - Finally, "If include reordering is harmful, put things in different
+ // blocks to prevent it" has been a recommendation for a long time that
+ // people are used to. We'll need a dev education push to change this to
+ // "If include reordering is harmful, put things in a different block and
+ // _prepend that with a comment_ to prevent it" before changing behavior.
+ ChromiumStyle.IncludeStyle.IncludeBlocks =
+ tooling::IncludeStyle::IBS_Preserve;
+
+ if (Language == FormatStyle::LK_Java) {
+ ChromiumStyle.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
+ ChromiumStyle.ContinuationIndentWidth = 8;
+ ChromiumStyle.IndentWidth = 4;
+ // See styleguide for import groups:
+ // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
+ ChromiumStyle.JavaImportGroups = {
+ "android",
+ "androidx",
+ "com",
+ "dalvik",
+ "junit",
+ "org",
+ "com.google.android.apps.chrome",
+ "org.chromium",
+ "java",
+ "javax",
+ };
+ } else if (Language == FormatStyle::LK_JavaScript) {
+ ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ ChromiumStyle.AllowShortLoopsOnASingleLine = false;
+ } else {
+ ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
+ ChromiumStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+ ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ ChromiumStyle.AllowShortLoopsOnASingleLine = false;
+ ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ ChromiumStyle.DerivePointerAlignment = false;
+ if (Language == FormatStyle::LK_ObjC)
+ ChromiumStyle.ColumnLimit = 80;
+ }
+ return ChromiumStyle;
+}
+
+FormatStyle getMozillaStyle() {
+ FormatStyle MozillaStyle = getLLVMStyle();
+ MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
+ MozillaStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+ MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
+ FormatStyle::DRTBS_TopLevel;
+ MozillaStyle.BinPackArguments = false;
+ MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
+ MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
+ MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+ MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+ MozillaStyle.ConstructorInitializerIndentWidth = 2;
+ MozillaStyle.ContinuationIndentWidth = 2;
+ MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
+ MozillaStyle.FixNamespaceComments = false;
+ MozillaStyle.IndentCaseLabels = true;
+ MozillaStyle.ObjCSpaceAfterProperty = true;
+ MozillaStyle.ObjCSpaceBeforeProtocolList = false;
+ MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
+ MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
+ MozillaStyle.SpaceAfterTemplateKeyword = false;
+ return MozillaStyle;
+}
+
+FormatStyle getWebKitStyle() {
+ FormatStyle Style = getLLVMStyle();
+ Style.AccessModifierOffset = -4;
+ Style.AlignAfterOpenBracket = false;
+ Style.AlignOperands = FormatStyle::OAS_DontAlign;
+ Style.AlignTrailingComments = {};
+ Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ Style.ColumnLimit = 0;
+ Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
+ Style.FixNamespaceComments = false;
+ Style.IndentWidth = 4;
+ Style.NamespaceIndentation = FormatStyle::NI_Inner;
+ Style.ObjCBlockIndentWidth = 4;
+ Style.ObjCSpaceAfterProperty = true;
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ Style.SpaceBeforeCpp11BracedList = true;
+ Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
+ return Style;
+}
+
+FormatStyle getGNUStyle() {
+ FormatStyle Style = getLLVMStyle();
+ Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
+ Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ Style.BreakBeforeBraces = FormatStyle::BS_GNU;
+ Style.BreakBeforeTernaryOperators = true;
+ Style.ColumnLimit = 79;
+ Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
+ Style.FixNamespaceComments = false;
+ Style.KeepFormFeed = true;
+ Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+ return Style;
+}
+
+FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
+ FormatStyle Style = getLLVMStyle(Language);
+ Style.ColumnLimit = 120;
+ Style.TabWidth = 4;
+ Style.IndentWidth = 4;
+ Style.UseTab = FormatStyle::UT_Never;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ Style.BraceWrapping.AfterEnum = true;
+ Style.BraceWrapping.AfterFunction = true;
+ Style.BraceWrapping.AfterNamespace = true;
+ Style.BraceWrapping.AfterObjCDeclaration = true;
+ Style.BraceWrapping.AfterStruct = true;
+ Style.BraceWrapping.AfterExternBlock = true;
+ Style.BraceWrapping.BeforeCatch = true;
+ Style.BraceWrapping.BeforeElse = true;
+ Style.BraceWrapping.BeforeWhile = false;
+ Style.PenaltyReturnTypeOnItsOwnLine = 1000;
+ Style.AllowShortEnumsOnASingleLine = false;
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ Style.AllowShortCaseLabelsOnASingleLine = false;
+ Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+ Style.AllowShortLoopsOnASingleLine = false;
+ Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
+ Style.BreakAfterReturnType = FormatStyle::RTBS_None;
+ return Style;
+}
+
+FormatStyle getClangFormatStyle() {
+ FormatStyle Style = getLLVMStyle();
+ Style.InsertBraces = true;
+ Style.InsertNewlineAtEOF = true;
+ Style.IntegerLiteralSeparator.Decimal = 3;
+ Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
+ Style.LineEnding = FormatStyle::LE_LF;
+ Style.RemoveBracesLLVM = true;
+ Style.RemoveEmptyLinesInUnwrappedLines = true;
+ Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+ Style.RemoveSemicolon = true;
+ return Style;
+}
+
+FormatStyle getNoStyle() {
+ FormatStyle NoStyle = getLLVMStyle();
+ NoStyle.DisableFormat = true;
+ NoStyle.SortIncludes = {};
+ NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
+ return NoStyle;
+}
+
+bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
+ FormatStyle *Style) {
+ constexpr StringRef Prefix("inheritparentconfig=");
+
+ if (Name.equals_insensitive("llvm"))
+ *Style = getLLVMStyle(Language);
+ else if (Name.equals_insensitive("chromium"))
+ *Style = getChromiumStyle(Language);
+ else if (Name.equals_insensitive("mozilla"))
+ *Style = getMozillaStyle();
+ else if (Name.equals_insensitive("google"))
+ *Style = getGoogleStyle(Language);
+ else if (Name.equals_insensitive("webkit"))
+ *Style = getWebKitStyle();
+ else if (Name.equals_insensitive("gnu"))
+ *Style = getGNUStyle();
+ else if (Name.equals_insensitive("microsoft"))
+ *Style = getMicrosoftStyle(Language);
+ else if (Name.equals_insensitive("clang-format"))
+ *Style = getClangFormatStyle();
+ else if (Name.equals_insensitive("none"))
+ *Style = getNoStyle();
+ else if (Name.equals_insensitive(Prefix.drop_back()))
+ Style->InheritConfig = "..";
+ else if (Name.size() > Prefix.size() && Name.starts_with_insensitive(Prefix))
+ Style->InheritConfig = Name.substr(Prefix.size());
+ else
+ return false;
+
+ Style->Language = Language;
+ return true;
+}
+
+ParseError validateQualifierOrder(FormatStyle *Style) {
+ // If its empty then it means don't do anything.
+ if (Style->QualifierOrder.empty())
+ return ParseError::MissingQualifierOrder;
+
+ // Ensure the list contains only currently valid qualifiers.
+ for (const auto &Qualifier : Style->QualifierOrder) {
+ if (Qualifier == "type")
+ continue;
+ auto token =
+ LeftRightQualifierAlignmentFixer::getTokenFromQualifier(Qualifier);
+ if (token == tok::identifier)
+ return ParseError::InvalidQualifierSpecified;
+ }
+
+ // Ensure the list is unique (no duplicates).
+ std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
+ Style->QualifierOrder.end());
+ if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
+ LLVM_DEBUG(llvm::dbgs()
+ << "Duplicate Qualifiers " << Style->QualifierOrder.size()
+ << " vs " << UniqueQualifiers.size() << "\n");
+ return ParseError::DuplicateQualifierSpecified;
+ }
+
+ // Ensure the list has 'type' in it.
+ if (!llvm::is_contained(Style->QualifierOrder, "type"))
+ return ParseError::MissingQualifierType;
+
+ return ParseError::Success;
+}
+
+std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
+ FormatStyle *Style, bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler,
+ void *DiagHandlerCtxt, bool IsDotHFile) {
+ assert(Style);
+ FormatStyle::LanguageKind Language = Style->Language;
+ assert(Language != FormatStyle::LK_None);
+ if (Config.getBuffer().trim().empty())
+ return make_error_code(ParseError::Success);
+ Style->StyleSet.Clear();
+ std::vector<FormatStyle> Styles;
+ llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
+ DiagHandlerCtxt);
+ // DocumentListTraits<vector<FormatStyle>> uses the context to get default
+ // values for the fields, keys for which are missing from the configuration.
+ // Mapping also uses the context to get the language to find the correct
+ // base style.
+ Input.setContext(Style);
+ Input.setAllowUnknownKeys(AllowUnknownOptions);
+ Input >> Styles;
+ if (Input.error())
+ return Input.error();
+ if (Styles.empty())
+ return make_error_code(ParseError::Success);
+
+ const auto StyleCount = Styles.size();
+
+ // Start from the second style as (only) the first one may be the default.
+ for (unsigned I = 1; I < StyleCount; ++I) {
+ const auto Lang = Styles[I].Language;
+ if (Lang == FormatStyle::LK_None)
+ return make_error_code(ParseError::Error);
+ // Ensure that each language is configured at most once.
+ for (unsigned J = 0; J < I; ++J) {
+ if (Lang == Styles[J].Language) {
+ LLVM_DEBUG(llvm::dbgs()
+ << "Duplicate languages in the config file on positions "
+ << J << " and " << I << '\n');
+ return make_error_code(ParseError::Error);
+ }
+ }
+ }
+
+ int LanguagePos = -1; // Position of the style for Language.
+ int CppPos = -1; // Position of the style for C++.
+ int CPos = -1; // Position of the style for C.
+
+ // Search Styles for Language and store the positions of C++ and C styles in
+ // case Language is not found.
+ for (unsigned I = 0; I < StyleCount; ++I) {
+ const auto Lang = Styles[I].Language;
+ if (Lang == Language) {
+ LanguagePos = I;
+ break;
+ }
+ if (Lang == FormatStyle::LK_Cpp)
+ CppPos = I;
+ else if (Lang == FormatStyle::LK_C)
+ CPos = I;
+ }
+
+ // If Language is not found, use the default style if there is one. Otherwise,
+ // use the C style for C++ .h files and for backward compatibility, the C++
+ // style for .c files.
+ if (LanguagePos < 0) {
+ if (Styles[0].Language == FormatStyle::LK_None) // Default style.
+ LanguagePos = 0;
+ else if (IsDotHFile && Language == FormatStyle::LK_Cpp)
+ LanguagePos = CPos;
+ else if (!IsDotHFile && Language == FormatStyle::LK_C)
+ LanguagePos = CppPos;
+ if (LanguagePos < 0)
+ return make_error_code(ParseError::Unsuitable);
+ }
+
+ for (const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
+ Style->StyleSet.Add(S);
+
+ *Style = Styles[LanguagePos];
+
+ if (LanguagePos == 0) {
+ if (Style->Language == FormatStyle::LK_None) // Default style.
+ Style->Language = Language;
+ Style->StyleSet.Add(*Style);
+ }
+
+ if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
+ Style->BinPackArguments) {
+ // See comment on FormatStyle::TSC_Wrapped.
+ return make_error_code(ParseError::BinPackTrailingCommaConflict);
+ }
+ if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
+ return make_error_code(validateQualifierOrder(Style));
+ return make_error_code(ParseError::Success);
+}
+
+std::string configurationAsText(const FormatStyle &Style) {
+ std::string Text;
+ llvm::raw_string_ostream Stream(Text);
+ llvm::yaml::Output Output(Stream);
+ // We use the same mapping method for input and output, so we need a non-const
+ // reference here.
+ FormatStyle NonConstStyle = Style;
+ expandPresetsBraceWrapping(NonConstStyle);
+ expandPresetsSpaceBeforeParens(NonConstStyle);
+ expandPresetsSpacesInParens(NonConstStyle);
+ Output << NonConstStyle;
+
+ return Stream.str();
+}
+
+std::optional<FormatStyle>
+FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
+ if (!Styles)
+ return std::nullopt;
+ auto It = Styles->find(Language);
+ if (It == Styles->end())
+ return std::nullopt;
+ FormatStyle Style = It->second;
+ Style.StyleSet = *this;
+ return Style;
+}
+
+void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
+ assert(Style.Language != LK_None &&
+ "Cannot add a style for LK_None to a StyleSet");
+ assert(
+ !Style.StyleSet.Styles &&
+ "Cannot add a style associated with an existing StyleSet to a StyleSet");
+ if (!Styles)
+ Styles = std::make_shared<MapType>();
+ (*Styles)[Style.Language] = std::move(Style);
+}
+
+void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
+
+std::optional<FormatStyle>
+FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
+ return StyleSet.Get(Language);
+}
+
+namespace {
+
+void replaceToken(const FormatToken &Token, FormatToken *Next,
+ const SourceManager &SourceMgr, tooling::Replacements &Result,
+ StringRef Text = "") {
+ const auto &Tok = Token.Tok;
+ SourceLocation Start;
+ if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
+ Start = Tok.getLocation();
+ Next->WhitespaceRange = Token.WhitespaceRange;
+ } else {
+ Start = Token.WhitespaceRange.getBegin();
+ }
+ const auto &Range = CharSourceRange::getCharRange(Start, Tok.getEndLoc());
+ cantFail(Result.add(tooling::Replacement(SourceMgr, Range, Text)));
+}
+
+class ParensRemover : public TokenAnalyzer {
+public:
+ ParensRemover(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ removeParens(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ const auto &SourceMgr = Env.getSourceManager();
+ for (auto *Line : Lines) {
+ if (!Line->Children.empty())
+ removeParens(Line->Children, Result);
+ if (!Line->Affected)
+ continue;
+ for (const auto *Token = Line->First; Token && !Token->Finalized;
+ Token = Token->Next) {
+ if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
+ replaceToken(*Token, Token->Next, SourceMgr, Result, " ");
+ }
+ }
+ }
+};
+
+class BracesInserter : public TokenAnalyzer {
+public:
+ BracesInserter(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ insertBraces(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ const auto &SourceMgr = Env.getSourceManager();
+ int OpeningBraceSurplus = 0;
+ for (AnnotatedLine *Line : Lines) {
+ if (!Line->Children.empty())
+ insertBraces(Line->Children, Result);
+ if (!Line->Affected && OpeningBraceSurplus == 0)
+ continue;
+ for (FormatToken *Token = Line->First; Token && !Token->Finalized;
+ Token = Token->Next) {
+ int BraceCount = Token->BraceCount;
+ if (BraceCount == 0)
+ continue;
+ std::string Brace;
+ if (BraceCount < 0) {
+ assert(BraceCount == -1);
+ if (!Line->Affected)
+ break;
+ Brace = Token->is(tok::comment) ? "\n{" : "{";
+ ++OpeningBraceSurplus;
+ } else {
+ if (OpeningBraceSurplus == 0)
+ break;
+ if (OpeningBraceSurplus < BraceCount)
+ BraceCount = OpeningBraceSurplus;
+ Brace = '\n' + std::string(BraceCount, '}');
+ OpeningBraceSurplus -= BraceCount;
+ }
+ Token->BraceCount = 0;
+ const auto Start = Token->Tok.getEndLoc();
+ cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
+ }
+ }
+ assert(OpeningBraceSurplus == 0);
+ }
+};
+
+class BracesRemover : public TokenAnalyzer {
+public:
+ BracesRemover(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ removeBraces(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ const auto &SourceMgr = Env.getSourceManager();
+ const auto *End = Lines.end();
+ for (const auto *I = Lines.begin(); I != End; ++I) {
+ const auto &Line = *I;
+ if (!Line->Children.empty())
+ removeBraces(Line->Children, Result);
+ if (!Line->Affected)
+ continue;
+ const auto *NextLine = I + 1 == End ? nullptr : I[1];
+ for (const auto *Token = Line->First; Token && !Token->Finalized;
+ Token = Token->Next) {
+ if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
+ continue;
+ auto *Next = Token->Next;
+ assert(Next || Token == Line->Last);
+ if (!Next && NextLine)
+ Next = NextLine->First;
+ replaceToken(*Token, Next, SourceMgr, Result);
+ }
+ }
+ }
+};
+
+class SemiRemover : public TokenAnalyzer {
+public:
+ SemiRemover(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ removeSemi(Annotator, AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ void removeSemi(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ auto PrecededByFunctionRBrace = [](const FormatToken &Tok) {
+ const auto *Prev = Tok.Previous;
+ if (!Prev || Prev->isNot(tok::r_brace))
+ return false;
+ const auto *LBrace = Prev->MatchingParen;
+ return LBrace && LBrace->is(TT_FunctionLBrace);
+ };
+ const auto &SourceMgr = Env.getSourceManager();
+ const auto *End = Lines.end();
+ for (const auto *I = Lines.begin(); I != End; ++I) {
+ const auto &Line = *I;
+ if (!Line->Children.empty())
+ removeSemi(Annotator, Line->Children, Result);
+ if (!Line->Affected)
+ continue;
+ Annotator.calculateFormattingInformation(*Line);
+ const auto *NextLine = I + 1 == End ? nullptr : I[1];
+ for (const auto *Token = Line->First; Token && !Token->Finalized;
+ Token = Token->Next) {
+ if (Token->isNot(tok::semi) ||
+ (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
+ continue;
+ }
+ auto *Next = Token->Next;
+ assert(Next || Token == Line->Last);
+ if (!Next && NextLine)
+ Next = NextLine->First;
+ replaceToken(*Token, Next, SourceMgr, Result);
+ }
+ }
+ }
+};
+
+class EnumTrailingCommaEditor : public TokenAnalyzer {
+public:
+ EnumTrailingCommaEditor(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ editEnumTrailingComma(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ bool InEnumBraces = false;
+ const FormatToken *BeforeRBrace = nullptr;
+ const auto &SourceMgr = Env.getSourceManager();
+ for (auto *Line : Lines) {
+ if (!Line->Children.empty())
+ editEnumTrailingComma(Line->Children, Result);
+ for (const auto *Token = Line->First; Token && !Token->Finalized;
+ Token = Token->Next) {
+ if (Token->isNot(TT_EnumRBrace)) {
+ if (Token->is(TT_EnumLBrace))
+ InEnumBraces = true;
+ else if (InEnumBraces && Token->isNot(tok::comment))
+ BeforeRBrace = Line->Affected ? Token : nullptr;
+ continue;
+ }
+ InEnumBraces = false;
+ if (!BeforeRBrace) // Empty braces or Line not affected.
+ continue;
+ if (BeforeRBrace->is(tok::comma)) {
+ if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
+ replaceToken(*BeforeRBrace, BeforeRBrace->Next, SourceMgr, Result);
+ } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
+ cantFail(Result.add(tooling::Replacement(
+ SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0, ",")));
+ }
+ BeforeRBrace = nullptr;
+ }
+ }
+ }
+};
+
+class JavaScriptRequoter : public TokenAnalyzer {
+public:
+ JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ requoteJSStringLiteral(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ // Replaces double/single-quoted string literal as appropriate, re-escaping
+ // the contents in the process.
+ void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ for (AnnotatedLine *Line : Lines) {
+ requoteJSStringLiteral(Line->Children, Result);
+ if (!Line->Affected)
+ continue;
+ for (FormatToken *FormatTok = Line->First; FormatTok;
+ FormatTok = FormatTok->Next) {
+ StringRef Input = FormatTok->TokenText;
+ if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
+ // NB: testing for not starting with a double quote to avoid
+ // breaking `template strings`.
+ (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
+ !Input.starts_with("\"")) ||
+ (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
+ !Input.starts_with("\'"))) {
+ continue;
+ }
+
+ // Change start and end quote.
+ bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
+ SourceLocation Start = FormatTok->Tok.getLocation();
+ auto Replace = [&](SourceLocation Start, unsigned Length,
+ StringRef ReplacementText) {
+ auto Err = Result.add(tooling::Replacement(
+ Env.getSourceManager(), Start, Length, ReplacementText));
+ // FIXME: handle error. For now, print error message and skip the
+ // replacement for release version.
+ if (Err) {
+ llvm::errs() << toString(std::move(Err)) << "\n";
+ assert(false);
+ }
+ };
+ Replace(Start, 1, IsSingle ? "'" : "\"");
+ Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
+ IsSingle ? "'" : "\"");
+
+ // Escape internal quotes.
+ bool Escaped = false;
+ for (size_t i = 1; i < Input.size() - 1; i++) {
+ switch (Input[i]) {
+ case '\\':
+ if (!Escaped && i + 1 < Input.size() &&
+ ((IsSingle && Input[i + 1] == '"') ||
+ (!IsSingle && Input[i + 1] == '\''))) {
+ // Remove this \, it's escaping a " or ' that no longer needs
+ // escaping
+ Replace(Start.getLocWithOffset(i), 1, "");
+ continue;
+ }
+ Escaped = !Escaped;
+ break;
+ case '\"':
+ case '\'':
+ if (!Escaped && IsSingle == (Input[i] == '\'')) {
+ // Escape the quote.
+ Replace(Start.getLocWithOffset(i), 0, "\\");
+ }
+ Escaped = false;
+ break;
+ default:
+ Escaped = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+};
+
+class Formatter : public TokenAnalyzer {
+public:
+ Formatter(const Environment &Env, const FormatStyle &Style,
+ FormattingAttemptStatus *Status)
+ : TokenAnalyzer(Env, Style), Status(Status) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ tooling::Replacements Result;
+ deriveLocalStyle(AnnotatedLines);
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ for (AnnotatedLine *Line : AnnotatedLines)
+ Annotator.calculateFormattingInformation(*Line);
+ Annotator.setCommentLineLevels(AnnotatedLines);
+
+ WhitespaceManager Whitespaces(
+ Env.getSourceManager(), Style,
+ Style.LineEnding > FormatStyle::LE_CRLF
+ ? WhitespaceManager::inputUsesCRLF(
+ Env.getSourceManager().getBufferData(Env.getFileID()),
+ Style.LineEnding == FormatStyle::LE_DeriveCRLF)
+ : Style.LineEnding == FormatStyle::LE_CRLF);
+ ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
+ Env.getSourceManager(), Whitespaces, Encoding,
+ BinPackInconclusiveFunctions);
+ unsigned Penalty =
+ UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
+ Tokens.getKeywords(), Env.getSourceManager(),
+ Status)
+ .format(AnnotatedLines, /*DryRun=*/false,
+ /*AdditionalIndent=*/0,
+ /*FixBadIndentation=*/false,
+ /*FirstStartColumn=*/Env.getFirstStartColumn(),
+ /*NextStartColumn=*/Env.getNextStartColumn(),
+ /*LastStartColumn=*/Env.getLastStartColumn());
+ for (const auto &R : Whitespaces.generateReplacements())
+ if (Result.add(R))
+ return std::make_pair(Result, 0);
+ return std::make_pair(Result, Penalty);
+ }
+
+private:
+ bool
+ hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
+ for (const AnnotatedLine *Line : Lines) {
+ if (hasCpp03IncompatibleFormat(Line->Children))
+ return true;
+ for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
+ if (!Tok->hasWhitespaceBefore()) {
+ if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
+ return true;
+ if (Tok->is(TT_TemplateCloser) &&
+ Tok->Previous->is(TT_TemplateCloser)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
+ int AlignmentDiff = 0;
+
+ for (const AnnotatedLine *Line : Lines) {
+ AlignmentDiff += countVariableAlignments(Line->Children);
+
+ for (const auto *Tok = Line->getFirstNonComment(); Tok; Tok = Tok->Next) {
+ if (Tok->isNot(TT_PointerOrReference))
+ continue;
+
+ const auto *Prev = Tok->Previous;
+ const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
+ const bool SpaceBefore = Tok->hasWhitespaceBefore();
+
+ // e.g. `int **`, `int*&`, etc.
+ while (Tok->Next && Tok->Next->is(TT_PointerOrReference))
+ Tok = Tok->Next;
+
+ const auto *Next = Tok->Next;
+ const bool FollowedByName = Next && Next->Tok.getIdentifierInfo();
+ const bool SpaceAfter = Next && Next->hasWhitespaceBefore();
+
+ if ((!PrecededByName && !FollowedByName) ||
+ // e.g. `int * i` or `int*i`
+ (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
+ continue;
+ }
+
+ if ((PrecededByName && SpaceBefore) ||
+ (FollowedByName && !SpaceAfter)) {
+ // Right alignment.
+ ++AlignmentDiff;
+ } else if ((PrecededByName && !SpaceBefore) ||
+ (FollowedByName && SpaceAfter)) {
+ // Left alignment.
+ --AlignmentDiff;
+ }
+ }
+ }
+
+ return AlignmentDiff;
+ }
+
+ void
+ deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
+ bool HasBinPackedFunction = false;
+ bool HasOnePerLineFunction = false;
+ for (AnnotatedLine *Line : AnnotatedLines) {
+ if (!Line->First->Next)
+ continue;
+ FormatToken *Tok = Line->First->Next;
+ while (Tok->Next) {
+ if (Tok->is(PPK_BinPacked))
+ HasBinPackedFunction = true;
+ if (Tok->is(PPK_OnePerLine))
+ HasOnePerLineFunction = true;
+
+ Tok = Tok->Next;
+ }
+ }
+ if (Style.DerivePointerAlignment) {
+ const auto NetRightCount = countVariableAlignments(AnnotatedLines);
+ if (NetRightCount > 0)
+ Style.PointerAlignment = FormatStyle::PAS_Right;
+ else if (NetRightCount < 0)
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
+ }
+ if (Style.Standard == FormatStyle::LS_Auto) {
+ Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
+ ? FormatStyle::LS_Latest
+ : FormatStyle::LS_Cpp03;
+ }
+ BinPackInconclusiveFunctions =
+ HasBinPackedFunction || !HasOnePerLineFunction;
+ }
+
+ bool BinPackInconclusiveFunctions;
+ FormattingAttemptStatus *Status;
+};
+
+/// TrailingCommaInserter inserts trailing commas into container literals.
+/// E.g.:
+/// const x = [
+/// 1,
+/// ];
+/// TrailingCommaInserter runs after formatting. To avoid causing a required
+/// reformatting (and thus reflow), it never inserts a comma that'd exceed the
+/// ColumnLimit.
+///
+/// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
+/// is conceptually incompatible with bin packing.
+class TrailingCommaInserter : public TokenAnalyzer {
+public:
+ TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+ tooling::Replacements Result;
+ insertTrailingCommas(AnnotatedLines, Result);
+ return {Result, 0};
+ }
+
+private:
+ /// Inserts trailing commas in [] and {} initializers if they wrap over
+ /// multiple lines.
+ void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
+ tooling::Replacements &Result) {
+ for (AnnotatedLine *Line : Lines) {
+ insertTrailingCommas(Line->Children, Result);
+ if (!Line->Affected)
+ continue;
+ for (FormatToken *FormatTok = Line->First; FormatTok;
+ FormatTok = FormatTok->Next) {
+ if (FormatTok->NewlinesBefore == 0)
+ continue;
+ FormatToken *Matching = FormatTok->MatchingParen;
+ if (!Matching || !FormatTok->getPreviousNonComment())
+ continue;
+ if (!(FormatTok->is(tok::r_square) &&
+ Matching->is(TT_ArrayInitializerLSquare)) &&
+ !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
+ continue;
+ }
+ FormatToken *Prev = FormatTok->getPreviousNonComment();
+ if (Prev->is(tok::comma) || Prev->is(tok::semi))
+ continue;
+ // getEndLoc is not reliably set during re-lexing, use text length
+ // instead.
+ SourceLocation Start =
+ Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
+ // If inserting a comma would push the code over the column limit, skip
+ // this location - it'd introduce an unstable formatting due to the
+ // required reflow.
+ unsigned ColumnNumber =
+ Env.getSourceManager().getSpellingColumnNumber(Start);
+ if (ColumnNumber > Style.ColumnLimit)
+ continue;
+ // Comma insertions cannot conflict with each other, and this pass has a
+ // clean set of Replacements, so the operation below cannot fail.
+ cantFail(Result.add(
+ tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
+ }
+ }
+ }
+};
+
+// This class clean up the erroneous/redundant code around the given ranges in
+// file.
+class Cleaner : public TokenAnalyzer {
+public:
+ Cleaner(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style),
+ DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
+
+ // FIXME: eliminate unused parameters.
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ // FIXME: in the current implementation the granularity of affected range
+ // is an annotated line. However, this is not sufficient. Furthermore,
+ // redundant code introduced by replacements does not necessarily
+ // intercept with ranges of replacements that result in the redundancy.
+ // To determine if some redundant code is actually introduced by
+ // replacements(e.g. deletions), we need to come up with a more
+ // sophisticated way of computing affected ranges.
+ AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+
+ checkEmptyNamespace(AnnotatedLines);
+
+ for (auto *Line : AnnotatedLines)
+ cleanupLine(Line);
+
+ return {generateFixes(), 0};
+ }
+
+private:
+ void cleanupLine(AnnotatedLine *Line) {
+ for (auto *Child : Line->Children)
+ cleanupLine(Child);
+
+ if (Line->Affected) {
+ cleanupRight(Line->First, tok::comma, tok::comma);
+ cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
+ cleanupRight(Line->First, tok::l_paren, tok::comma);
+ cleanupLeft(Line->First, tok::comma, tok::r_paren);
+ cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
+ cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
+ cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
+ }
+ }
+
+ bool containsOnlyComments(const AnnotatedLine &Line) {
+ for (FormatToken *Tok = Line.First; Tok; Tok = Tok->Next)
+ if (Tok->isNot(tok::comment))
+ return false;
+ return true;
+ }
+
+ // Iterate through all lines and remove any empty (nested) namespaces.
+ void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
+ std::set<unsigned> DeletedLines;
+ for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
+ auto &Line = *AnnotatedLines[i];
+ if (Line.startsWithNamespace())
+ checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
+ }
+
+ for (auto Line : DeletedLines) {
+ FormatToken *Tok = AnnotatedLines[Line]->First;
+ while (Tok) {
+ deleteToken(Tok);
+ Tok = Tok->Next;
+ }
+ }
+ }
+
+ // The function checks if the namespace, which starts from \p CurrentLine, and
+ // its nested namespaces are empty and delete them if they are empty. It also
+ // sets \p NewLine to the last line checked.
+ // Returns true if the current namespace is empty.
+ bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ unsigned CurrentLine, unsigned &NewLine,
+ std::set<unsigned> &DeletedLines) {
+ unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
+ if (Style.BraceWrapping.AfterNamespace) {
+ // If the left brace is in a new line, we should consume it first so that
+ // it does not make the namespace non-empty.
+ // FIXME: error handling if there is no left brace.
+ if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
+ NewLine = CurrentLine;
+ return false;
+ }
+ } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
+ return false;
+ }
+ while (++CurrentLine < End) {
+ if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
+ break;
+
+ if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
+ if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
+ DeletedLines)) {
+ return false;
+ }
+ CurrentLine = NewLine;
+ continue;
+ }
+
+ if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
+ continue;
+
+ // If there is anything other than comments or nested namespaces in the
+ // current namespace, the namespace cannot be empty.
+ NewLine = CurrentLine;
+ return false;
+ }
+
+ NewLine = CurrentLine;
+ if (CurrentLine >= End)
+ return false;
+
+ // Check if the empty namespace is actually affected by changed ranges.
+ if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
+ AnnotatedLines[InitLine]->First->Tok.getLocation(),
+ AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
+ return false;
+ }
+
+ for (unsigned i = InitLine; i <= CurrentLine; ++i)
+ DeletedLines.insert(i);
+
+ return true;
+ }
+
+ // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
+ // of the token in the pair if the left token has \p LK token kind and the
+ // right token has \p RK token kind. If \p DeleteLeft is true, the left token
+ // is deleted on match; otherwise, the right token is deleted.
+ template <typename LeftKind, typename RightKind>
+ void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
+ bool DeleteLeft) {
+ auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
+ for (auto *Res = Tok.Next; Res; Res = Res->Next) {
+ if (Res->isNot(tok::comment) &&
+ DeletedTokens.find(Res) == DeletedTokens.end()) {
+ return Res;
+ }
+ }
+ return nullptr;
+ };
+ for (auto *Left = Start; Left;) {
+ auto *Right = NextNotDeleted(*Left);
+ if (!Right)
+ break;
+ if (Left->is(LK) && Right->is(RK)) {
+ deleteToken(DeleteLeft ? Left : Right);
+ for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
+ deleteToken(Tok);
+ // If the right token is deleted, we should keep the left token
+ // unchanged and pair it with the new right token.
+ if (!DeleteLeft)
+ continue;
+ }
+ Left = Right;
+ }
+ }
+
+ template <typename LeftKind, typename RightKind>
+ void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
+ cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
+ }
+
+ template <typename LeftKind, typename RightKind>
+ void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
+ cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
+ }
+
+ // Delete the given token.
+ inline void deleteToken(FormatToken *Tok) {
+ if (Tok)
+ DeletedTokens.insert(Tok);
+ }
+
+ tooling::Replacements generateFixes() {
+ tooling::Replacements Fixes;
+ SmallVector<FormatToken *> Tokens;
+ std::copy(DeletedTokens.begin(), DeletedTokens.end(),
+ std::back_inserter(Tokens));
+
+ // Merge multiple continuous token deletions into one big deletion so that
+ // the number of replacements can be reduced. This makes computing affected
+ // ranges more efficient when we run reformat on the changed code.
+ unsigned Idx = 0;
+ while (Idx < Tokens.size()) {
+ unsigned St = Idx, End = Idx;
+ while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
+ ++End;
+ auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
+ Tokens[End]->Tok.getEndLoc());
+ auto Err =
+ Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
+ // FIXME: better error handling. for now just print error message and skip
+ // for the release version.
+ if (Err) {
+ llvm::errs() << toString(std::move(Err)) << "\n";
+ assert(false && "Fixes must not conflict!");
+ }
+ Idx = End + 1;
+ }
+
+ return Fixes;
+ }
+
+ // Class for less-than inequality comparason for the set `RedundantTokens`.
+ // We store tokens in the order they appear in the translation unit so that
+ // we do not need to sort them in `generateFixes()`.
+ struct FormatTokenLess {
+ FormatTokenLess(const SourceManager &SM) : SM(SM) {}
+
+ bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
+ return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
+ RHS->Tok.getLocation());
+ }
+ const SourceManager &SM;
+ };
+
+ // Tokens to be deleted.
+ std::set<FormatToken *, FormatTokenLess> DeletedTokens;
+};
+
+class ObjCHeaderStyleGuesser : public TokenAnalyzer {
+public:
+ ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
+ : TokenAnalyzer(Env, Style), IsObjC(false) {}
+
+ std::pair<tooling::Replacements, unsigned>
+ analyze(TokenAnnotator &Annotator,
+ SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ FormatTokenLexer &Tokens) override {
+ assert(Style.Language == FormatStyle::LK_Cpp);
+ IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
+ Tokens.getKeywords());
+ tooling::Replacements Result;
+ return {Result, 0};
+ }
+
+ bool isObjC() { return IsObjC; }
+
+private:
+ static bool
+ guessIsObjC(const SourceManager &SourceManager,
+ const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
+ const AdditionalKeywords &Keywords) {
+ // Keep this array sorted, since we are binary searching over it.
+ static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
+ "CGFloat",
+ "CGPoint",
+ "CGPointMake",
+ "CGPointZero",
+ "CGRect",
+ "CGRectEdge",
+ "CGRectInfinite",
+ "CGRectMake",
+ "CGRectNull",
+ "CGRectZero",
+ "CGSize",
+ "CGSizeMake",
+ "CGVector",
+ "CGVectorMake",
+ "FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
+ "FOUNDATION_EXTERN",
+ "NSAffineTransform",
+ "NSArray",
+ "NSAttributedString",
+ "NSBlockOperation",
+ "NSBundle",
+ "NSCache",
+ "NSCalendar",
+ "NSCharacterSet",
+ "NSCountedSet",
+ "NSData",
+ "NSDataDetector",
+ "NSDecimal",
+ "NSDecimalNumber",
+ "NSDictionary",
+ "NSEdgeInsets",
+ "NSError",
+ "NSErrorDomain",
+ "NSHashTable",
+ "NSIndexPath",
+ "NSIndexSet",
+ "NSInteger",
+ "NSInvocationOperation",
+ "NSLocale",
+ "NSMapTable",
+ "NSMutableArray",
+ "NSMutableAttributedString",
+ "NSMutableCharacterSet",
+ "NSMutableData",
+ "NSMutableDictionary",
+ "NSMutableIndexSet",
+ "NSMutableOrderedSet",
+ "NSMutableSet",
+ "NSMutableString",
+ "NSNumber",
+ "NSNumberFormatter",
+ "NSObject",
+ "NSOperation",
+ "NSOperationQueue",
+ "NSOperationQueuePriority",
+ "NSOrderedSet",
+ "NSPoint",
+ "NSPointerArray",
+ "NSQualityOfService",
+ "NSRange",
+ "NSRect",
+ "NSRegularExpression",
+ "NSSet",
+ "NSSize",
+ "NSString",
+ "NSTimeZone",
+ "NSUInteger",
+ "NSURL",
+ "NSURLComponents",
+ "NSURLQueryItem",
+ "NSUUID",
+ "NSValue",
+ "NS_ASSUME_NONNULL_BEGIN",
+ "UIImage",
+ "UIView",
+ };
+ assert(llvm::is_sorted(FoundationIdentifiers));
+
+ for (auto *Line : AnnotatedLines) {
+ if (Line->First && (Line->First->TokenText.starts_with("#") ||
+ Line->First->TokenText == "__pragma" ||
+ Line->First->TokenText == "_Pragma")) {
+ continue;
+ }
+ for (const FormatToken *FormatTok = Line->First; FormatTok;
+ FormatTok = FormatTok->Next) {
+ if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
+ (FormatTok->isNot(tok::objc_not_keyword) ||
+ FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
+ tok::l_brace))) ||
+ (FormatTok->Tok.isAnyIdentifier() &&
+ llvm::binary_search(FoundationIdentifiers,
+ FormatTok->TokenText)) ||
+ FormatTok->is(TT_ObjCStringLiteral) ||
+ FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
+ Keywords.kw_NS_ERROR_ENUM,
+ Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
+ TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
+ TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
+ TT_ObjCProperty, TT_ObjCSelector)) {
+ LLVM_DEBUG(llvm::dbgs()
+ << "Detected ObjC at location "
+ << FormatTok->Tok.getLocation().printToString(
+ SourceManager)
+ << " token: " << FormatTok->TokenText << " token type: "
+ << getTokenTypeName(FormatTok->getType()) << "\n");
+ return true;
+ }
+ }
+ if (guessIsObjC(SourceManager, Line->Children, Keywords))
+ return true;
+ }
+ return false;
+ }
+
+ bool IsObjC;
+};
+
+struct IncludeDirective {
+ StringRef Filename;
+ StringRef Text;
+ unsigned Offset;
+ int Category;
+ int Priority;
+};
+
+struct JavaImportDirective {
+ StringRef Identifier;
+ StringRef Text;
+ unsigned Offset;
+ SmallVector<StringRef> AssociatedCommentLines;
+ bool IsStatic;
+};
+
+} // end anonymous namespace
+
+// Determines whether 'Ranges' intersects with ('Start', 'End').
+static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
+ unsigned End) {
+ for (const auto &Range : Ranges) {
+ if (Range.getOffset() < End &&
+ Range.getOffset() + Range.getLength() > Start) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
+// before sorting/deduplicating. Index is the index of the include under the
+// cursor in the original set of includes. If this include has duplicates, it is
+// the index of the first of the duplicates as the others are going to be
+// removed. OffsetToEOL describes the cursor's position relative to the end of
+// its current line.
+// If `Cursor` is not on any #include, `Index` will be
+// std::numeric_limits<unsigned>::max().
+static std::pair<unsigned, unsigned>
+FindCursorIndex(const ArrayRef<IncludeDirective> &Includes,
+ const ArrayRef<unsigned> &Indices, unsigned Cursor) {
+ unsigned CursorIndex = std::numeric_limits<unsigned>::max();
+ unsigned OffsetToEOL = 0;
+ for (int i = 0, e = Includes.size(); i != e; ++i) {
+ unsigned Start = Includes[Indices[i]].Offset;
+ unsigned End = Start + Includes[Indices[i]].Text.size();
+ if (!(Cursor >= Start && Cursor < End))
+ continue;
+ CursorIndex = Indices[i];
+ OffsetToEOL = End - Cursor;
+ // Put the cursor on the only remaining #include among the duplicate
+ // #includes.
+ while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
+ CursorIndex = i;
+ break;
+ }
+ return std::make_pair(CursorIndex, OffsetToEOL);
+}
+
+// Replace all "\r\n" with "\n".
+std::string replaceCRLF(const std::string &Code) {
+ std::string NewCode;
+ size_t Pos = 0, LastPos = 0;
+
+ do {
+ Pos = Code.find("\r\n", LastPos);
+ if (Pos == LastPos) {
+ ++LastPos;
+ continue;
+ }
+ if (Pos == std::string::npos) {
+ NewCode += Code.substr(LastPos);
+ break;
+ }
+ NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
+ LastPos = Pos + 2;
+ } while (Pos != std::string::npos);
+
+ return NewCode;
+}
+
+// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
+// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
+// source order.
+// #include directives with the same text will be deduplicated, and only the
+// first #include in the duplicate #includes remains. If the `Cursor` is
+// provided and put on a deleted #include, it will be moved to the remaining
+// #include in the duplicate #includes.
+static void sortCppIncludes(const FormatStyle &Style,
+ const ArrayRef<IncludeDirective> &Includes,
+ ArrayRef<tooling::Range> Ranges, StringRef FileName,
+ StringRef Code, tooling::Replacements &Replaces,
+ unsigned *Cursor) {
+ tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
+ const unsigned IncludesBeginOffset = Includes.front().Offset;
+ const unsigned IncludesEndOffset =
+ Includes.back().Offset + Includes.back().Text.size();
+ const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
+ if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
+ return;
+ SmallVector<unsigned, 16> Indices =
+ llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
+
+ if (Style.SortIncludes.Enabled) {
+ stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
+ SmallString<128> LHSStem, RHSStem;
+ if (Style.SortIncludes.IgnoreExtension) {
+ LHSStem = Includes[LHSI].Filename;
+ RHSStem = Includes[RHSI].Filename;
+ llvm::sys::path::replace_extension(LHSStem, "");
+ llvm::sys::path::replace_extension(RHSStem, "");
+ }
+ std::string LHSStemLower, RHSStemLower;
+ std::string LHSFilenameLower, RHSFilenameLower;
+ if (Style.SortIncludes.IgnoreCase) {
+ LHSStemLower = LHSStem.str().lower();
+ RHSStemLower = RHSStem.str().lower();
+ LHSFilenameLower = Includes[LHSI].Filename.lower();
+ RHSFilenameLower = Includes[RHSI].Filename.lower();
+ }
+ return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
+ LHSFilenameLower, Includes[LHSI].Filename) <
+ std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
+ RHSFilenameLower, Includes[RHSI].Filename);
+ });
+ }
+
+ // The index of the include on which the cursor will be put after
+ // sorting/deduplicating.
+ unsigned CursorIndex;
+ // The offset from cursor to the end of line.
+ unsigned CursorToEOLOffset;
+ if (Cursor) {
+ std::tie(CursorIndex, CursorToEOLOffset) =
+ FindCursorIndex(Includes, Indices, *Cursor);
+ }
+
+ // Deduplicate #includes.
+ Indices.erase(llvm::unique(Indices,
+ [&](unsigned LHSI, unsigned RHSI) {
+ return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
+ }),
+ Indices.end());
+
+ int CurrentCategory = Includes.front().Category;
+
+ // If the #includes are out of order, we generate a single replacement fixing
+ // the entire block. Otherwise, no replacement is generated.
+ // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
+ // enough as additional newlines might be added or removed across #include
+ // blocks. This we handle below by generating the updated #include blocks and
+ // comparing it to the original.
+ if (Indices.size() == Includes.size() && is_sorted(Indices) &&
+ Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) {
+ return;
+ }
+
+ const auto OldCursor = Cursor ? *Cursor : 0;
+ std::string result;
+ for (unsigned Index : Indices) {
+ if (!result.empty()) {
+ result += "\n";
+ if (Style.IncludeStyle.IncludeBlocks ==
+ tooling::IncludeStyle::IBS_Regroup &&
+ CurrentCategory != Includes[Index].Category) {
+ result += "\n";
+ }
+ }
+ result += Includes[Index].Text;
+ if (Cursor && CursorIndex == Index)
+ *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
+ CurrentCategory = Includes[Index].Category;
+ }
+
+ if (Cursor && *Cursor >= IncludesEndOffset)
+ *Cursor += result.size() - IncludesBlockSize;
+
+ // If the #includes are out of order, we generate a single replacement fixing
+ // the entire range of blocks. Otherwise, no replacement is generated.
+ if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
+ IncludesBeginOffset, IncludesBlockSize)))) {
+ if (Cursor)
+ *Cursor = OldCursor;
+ return;
+ }
+
+ auto Err = Replaces.add(tooling::Replacement(
+ FileName, Includes.front().Offset, IncludesBlockSize, result));
+ // FIXME: better error handling. For now, just skip the replacement for the
+ // release version.
+ if (Err) {
+ llvm::errs() << toString(std::move(Err)) << "\n";
+ assert(false);
+ }
+}
+
+tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName,
+ tooling::Replacements &Replaces,
+ unsigned *Cursor) {
+ unsigned Prev = llvm::StringSwitch<size_t>(Code)
+ .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
+ .Default(0);
+ unsigned SearchFrom = 0;
+ SmallVector<StringRef, 4> Matches;
+ SmallVector<IncludeDirective, 16> IncludesInBlock;
+
+ // In compiled files, consider the first #include to be the main #include of
+ // the file if it is not a system #include. This ensures that the header
+ // doesn't have hidden dependencies
+ // (http://llvm.org/docs/CodingStandards.html#include-style).
+ //
+ // FIXME: Do some validation, e.g. edit distance of the base name, to fix
+ // cases where the first #include is unlikely to be the main header.
+ tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
+ bool FirstIncludeBlock = true;
+ bool MainIncludeFound = false;
+ bool FormattingOff = false;
+
+ // '[' must be the first and '-' the last character inside [...].
+ llvm::Regex RawStringRegex(
+ "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
+ SmallVector<StringRef, 2> RawStringMatches;
+ std::string RawStringTermination = ")\"";
+
+ for (const auto Size = Code.size(); SearchFrom < Size;) {
+ size_t Pos = SearchFrom;
+ if (Code[SearchFrom] != '\n') {
+ do { // Search for the first newline while skipping line splices.
+ ++Pos;
+ Pos = Code.find('\n', Pos);
+ } while (Pos != StringRef::npos && Code[Pos - 1] == '\\');
+ }
+
+ StringRef Line =
+ Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
+
+ StringRef Trimmed = Line.trim();
+
+ // #includes inside raw string literals need to be ignored.
+ // or we will sort the contents of the string.
+ // Skip past until we think we are at the rawstring literal close.
+ if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
+ std::string CharSequence = RawStringMatches[1].str();
+ RawStringTermination = ")" + CharSequence + "\"";
+ FormattingOff = true;
+ }
+
+ if (Trimmed.contains(RawStringTermination))
+ FormattingOff = false;
+
+ bool IsBlockComment = false;
+
+ if (isClangFormatOff(Trimmed)) {
+ FormattingOff = true;
+ } else if (isClangFormatOn(Trimmed)) {
+ FormattingOff = false;
+ } else if (Trimmed.starts_with("/*")) {
+ IsBlockComment = true;
+ Pos = Code.find("*/", SearchFrom + 2);
+ }
+
+ const bool EmptyLineSkipped =
+ Trimmed.empty() &&
+ (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
+ Style.IncludeStyle.IncludeBlocks ==
+ tooling::IncludeStyle::IBS_Regroup);
+
+ bool MergeWithNextLine = Trimmed.ends_with("\\");
+ if (!FormattingOff && !MergeWithNextLine) {
+ if (!IsBlockComment &&
+ tooling::HeaderIncludes::IncludeRegex.match(Trimmed, &Matches)) {
+ StringRef IncludeName = Matches[2];
+ if (Trimmed.contains("/*") && !Trimmed.contains("*/")) {
+ // #include with a start of a block comment, but without the end.
+ // Need to keep all the lines until the end of the comment together.
+ // FIXME: This is somehow simplified check that probably does not work
+ // correctly if there are multiple comments on a line.
+ Pos = Code.find("*/", SearchFrom);
+ Line = Code.substr(
+ Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
+ }
+ int Category = Categories.getIncludePriority(
+ IncludeName,
+ /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
+ int Priority = Categories.getSortIncludePriority(
+ IncludeName, !MainIncludeFound && FirstIncludeBlock);
+ if (Category == 0)
+ MainIncludeFound = true;
+ IncludesInBlock.push_back(
+ {IncludeName, Line, Prev, Category, Priority});
+ } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
+ sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
+ Replaces, Cursor);
+ IncludesInBlock.clear();
+ if (Trimmed.starts_with("#pragma hdrstop")) // Precompiled headers.
+ FirstIncludeBlock = true;
+ else
+ FirstIncludeBlock = false;
+ }
+ }
+ if (Pos == StringRef::npos || Pos + 1 == Code.size())
+ break;
+
+ if (!MergeWithNextLine)
+ Prev = Pos + 1;
+ SearchFrom = Pos + 1;
+ }
+ if (!IncludesInBlock.empty()) {
+ sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
+ Cursor);
+ }
+ return Replaces;
+}
+
+// Returns group number to use as a first order sort on imports. Gives
+// std::numeric_limits<unsigned>::max() if the import does not match any given
+// groups.
+static unsigned findJavaImportGroup(const FormatStyle &Style,
+ StringRef ImportIdentifier) {
+ unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
+ unsigned LongestMatchLength = 0;
+ for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
+ const std::string &GroupPrefix = Style.JavaImportGroups[I];
+ if (ImportIdentifier.starts_with(GroupPrefix) &&
+ GroupPrefix.length() > LongestMatchLength) {
+ LongestMatchIndex = I;
+ LongestMatchLength = GroupPrefix.length();
+ }
+ }
+ return LongestMatchIndex;
+}
+
+// Sorts and deduplicates a block of includes given by 'Imports' based on
+// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
+// Import declarations with the same text will be deduplicated. Between each
+// import group, a newline is inserted, and within each import group, a
+// lexicographic sort based on ASCII value is performed.
+static void sortJavaImports(const FormatStyle &Style,
+ const ArrayRef<JavaImportDirective> &Imports,
+ ArrayRef<tooling::Range> Ranges, StringRef FileName,
+ StringRef Code, tooling::Replacements &Replaces) {
+ unsigned ImportsBeginOffset = Imports.front().Offset;
+ unsigned ImportsEndOffset =
+ Imports.back().Offset + Imports.back().Text.size();
+ unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
+ if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
+ return;
+
+ SmallVector<unsigned, 16> Indices =
+ llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
+ SmallVector<unsigned, 16> JavaImportGroups;
+ JavaImportGroups.reserve(Imports.size());
+ for (const JavaImportDirective &Import : Imports)
+ JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
+
+ bool StaticImportAfterNormalImport =
+ Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
+ sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
+ // Negating IsStatic to push static imports above non-static imports.
+ return std::make_tuple(!Imports[LHSI].IsStatic ^
+ StaticImportAfterNormalImport,
+ JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
+ std::make_tuple(!Imports[RHSI].IsStatic ^
+ StaticImportAfterNormalImport,
+ JavaImportGroups[RHSI], Imports[RHSI].Identifier);
+ });
+
+ // Deduplicate imports.
+ Indices.erase(llvm::unique(Indices,
+ [&](unsigned LHSI, unsigned RHSI) {
+ return Imports[LHSI].Text == Imports[RHSI].Text;
+ }),
+ Indices.end());
+
+ bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
+ unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
+
+ std::string result;
+ for (unsigned Index : Indices) {
+ if (!result.empty()) {
+ result += "\n";
+ if (CurrentIsStatic != Imports[Index].IsStatic ||
+ CurrentImportGroup != JavaImportGroups[Index]) {
+ result += "\n";
+ }
+ }
+ for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
+ result += CommentLine;
+ result += "\n";
+ }
+ result += Imports[Index].Text;
+ CurrentIsStatic = Imports[Index].IsStatic;
+ CurrentImportGroup = JavaImportGroups[Index];
+ }
+
+ // If the imports are out of order, we generate a single replacement fixing
+ // the entire block. Otherwise, no replacement is generated.
+ if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
+ Imports.front().Offset, ImportsBlockSize)))) {
+ return;
+ }
+
+ auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
+ ImportsBlockSize, result));
+ // FIXME: better error handling. For now, just skip the replacement for the
+ // release version.
+ if (Err) {
+ llvm::errs() << toString(std::move(Err)) << "\n";
+ assert(false);
+ }
+}
+
+namespace {
+
+constexpr StringRef
+ JavaImportRegexPattern("^import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;");
+
+constexpr StringRef JavaPackageRegexPattern("^package[\t ]");
+
+} // anonymous namespace
+
+tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName,
+ tooling::Replacements &Replaces) {
+ unsigned Prev = 0;
+ bool HasImport = false;
+ llvm::Regex ImportRegex(JavaImportRegexPattern);
+ llvm::Regex PackageRegex(JavaPackageRegexPattern);
+ SmallVector<StringRef, 4> Matches;
+ SmallVector<JavaImportDirective, 16> ImportsInBlock;
+ SmallVector<StringRef> AssociatedCommentLines;
+
+ for (bool FormattingOff = false;;) {
+ auto Pos = Code.find('\n', Prev);
+ auto GetLine = [&] {
+ return Code.substr(Prev,
+ (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
+ };
+ StringRef Line = GetLine();
+
+ StringRef Trimmed = Line.trim();
+ if (Trimmed.empty() || PackageRegex.match(Trimmed)) {
+ // Skip empty line and package statement.
+ } else if (isClangFormatOff(Trimmed)) {
+ FormattingOff = true;
+ } else if (isClangFormatOn(Trimmed)) {
+ FormattingOff = false;
+ } else if (Trimmed.starts_with("//")) {
+ // Associating comments within the imports with the nearest import below.
+ if (HasImport)
+ AssociatedCommentLines.push_back(Line);
+ } else if (Trimmed.starts_with("/*")) {
+ Pos = Code.find("*/", Pos + 2);
+ if (Pos != StringRef::npos)
+ Pos = Code.find('\n', Pos + 2);
+ if (HasImport) {
+ // Extend `Line` for a multiline comment to include all lines the
+ // comment spans.
+ Line = GetLine();
+ AssociatedCommentLines.push_back(Line);
+ }
+ } else if (ImportRegex.match(Trimmed, &Matches)) {
+ if (FormattingOff) {
+ // If at least one import line has formatting turned off, turn off
+ // formatting entirely.
+ return Replaces;
+ }
+ StringRef Static = Matches[1];
+ StringRef Identifier = Matches[2];
+ bool IsStatic = false;
+ if (Static.contains("static"))
+ IsStatic = true;
+ ImportsInBlock.push_back(
+ {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
+ HasImport = true;
+ AssociatedCommentLines.clear();
+ } else {
+ // `Trimmed` is neither empty, nor a comment or a package/import
+ // statement.
+ break;
+ }
+ if (Pos == StringRef::npos || Pos + 1 == Code.size())
+ break;
+ Prev = Pos + 1;
+ }
+ if (HasImport)
+ sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
+ return Replaces;
+}
+
+bool isMpegTS(StringRef Code) {
+ // MPEG transport streams use the ".ts" file extension. clang-format should
+ // not attempt to format those. MPEG TS' frame format starts with 0x47 every
+ // 189 bytes - detect that and return.
+ return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
+}
+
+bool isLikelyXml(StringRef Code) { return Code.ltrim().starts_with("<"); }
+
+tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName, unsigned *Cursor) {
+ tooling::Replacements Replaces;
+ if (!Style.SortIncludes.Enabled || Style.DisableFormat)
+ return Replaces;
+ if (isLikelyXml(Code))
+ return Replaces;
+ if (Style.isJavaScript()) {
+ if (isMpegTS(Code))
+ return Replaces;
+ return sortJavaScriptImports(Style, Code, Ranges, FileName);
+ }
+ if (Style.isJava())
+ return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
+ if (Style.isCpp())
+ sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
+ return Replaces;
+}
+
+template <typename T>
+static Expected<tooling::Replacements>
+processReplacements(T ProcessFunc, StringRef Code,
+ const tooling::Replacements &Replaces,
+ const FormatStyle &Style) {
+ if (Replaces.empty())
+ return tooling::Replacements();
+
+ auto NewCode = applyAllReplacements(Code, Replaces);
+ if (!NewCode)
+ return NewCode.takeError();
+ std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
+ StringRef FileName = Replaces.begin()->getFilePath();
+
+ tooling::Replacements FormatReplaces =
+ ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
+
+ return Replaces.merge(FormatReplaces);
+}
+
+Expected<tooling::Replacements>
+formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
+ const FormatStyle &Style) {
+ // We need to use lambda function here since there are two versions of
+ // `sortIncludes`.
+ auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
+ std::vector<tooling::Range> Ranges,
+ StringRef FileName) -> tooling::Replacements {
+ return sortIncludes(Style, Code, Ranges, FileName);
+ };
+ auto SortedReplaces =
+ processReplacements(SortIncludes, Code, Replaces, Style);
+ if (!SortedReplaces)
+ return SortedReplaces.takeError();
+
+ // We need to use lambda function here since there are two versions of
+ // `reformat`.
+ auto Reformat = [](const FormatStyle &Style, StringRef Code,
+ std::vector<tooling::Range> Ranges,
+ StringRef FileName) -> tooling::Replacements {
+ return reformat(Style, Code, Ranges, FileName);
+ };
+ return processReplacements(Reformat, Code, *SortedReplaces, Style);
+}
+
+namespace {
+
+inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
+ return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
+ Replace.getLength() == 0 &&
+ tooling::HeaderIncludes::IncludeRegex.match(
+ Replace.getReplacementText());
+}
+
+inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
+ return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
+ Replace.getLength() == 1;
+}
+
+// FIXME: insert empty lines between newly created blocks.
+tooling::Replacements
+fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
+ const FormatStyle &Style) {
+ if (!Style.isCpp())
+ return Replaces;
+
+ tooling::Replacements HeaderInsertions;
+ std::set<StringRef> HeadersToDelete;
+ tooling::Replacements Result;
+ for (const auto &R : Replaces) {
+ if (isHeaderInsertion(R)) {
+ // Replacements from \p Replaces must be conflict-free already, so we can
+ // simply consume the error.
+ consumeError(HeaderInsertions.add(R));
+ } else if (isHeaderDeletion(R)) {
+ HeadersToDelete.insert(R.getReplacementText());
+ } else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
+ llvm::errs() << "Insertions other than header #include insertion are "
+ "not supported! "
+ << R.getReplacementText() << "\n";
+ } else {
+ consumeError(Result.add(R));
+ }
+ }
+ if (HeaderInsertions.empty() && HeadersToDelete.empty())
+ return Replaces;
+
+ StringRef FileName = Replaces.begin()->getFilePath();
+ tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
+
+ for (const auto &Header : HeadersToDelete) {
+ tooling::Replacements Replaces =
+ Includes.remove(Header.trim("\"<>"), Header.starts_with("<"));
+ for (const auto &R : Replaces) {
+ auto Err = Result.add(R);
+ if (Err) {
+ // Ignore the deletion on conflict.
+ llvm::errs() << "Failed to add header deletion replacement for "
+ << Header << ": " << toString(std::move(Err)) << "\n";
+ }
+ }
+ }
+
+ SmallVector<StringRef, 4> Matches;
+ for (const auto &R : HeaderInsertions) {
+ auto IncludeDirective = R.getReplacementText();
+ bool Matched =
+ tooling::HeaderIncludes::IncludeRegex.match(IncludeDirective, &Matches);
+ assert(Matched && "Header insertion replacement must have replacement text "
+ "'#include ...'");
+ (void)Matched;
+ auto IncludeName = Matches[2];
+ auto Replace =
+ Includes.insert(IncludeName.trim("\"<>"), IncludeName.starts_with("<"),
+ tooling::IncludeDirective::Include);
+ if (Replace) {
+ auto Err = Result.add(*Replace);
+ if (Err) {
+ consumeError(std::move(Err));
+ unsigned NewOffset =
+ Result.getShiftedCodePosition(Replace->getOffset());
+ auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
+ Replace->getReplacementText());
+ Result = Result.merge(tooling::Replacements(Shifted));
+ }
+ }
+ }
+ return Result;
+}
+
+} // anonymous namespace
+
+Expected<tooling::Replacements>
+cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
+ const FormatStyle &Style) {
+ // We need to use lambda function here since there are two versions of
+ // `cleanup`.
+ auto Cleanup = [](const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName) -> tooling::Replacements {
+ return cleanup(Style, Code, Ranges, FileName);
+ };
+ // Make header insertion replacements insert new headers into correct blocks.
+ tooling::Replacements NewReplaces =
+ fixCppIncludeInsertions(Code, Replaces, Style);
+ return cantFail(processReplacements(Cleanup, Code, NewReplaces, Style));
+}
+
+namespace internal {
+std::pair<tooling::Replacements, unsigned>
+reformat(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
+ unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
+ FormattingAttemptStatus *Status) {
+ FormatStyle Expanded = Style;
+ expandPresetsBraceWrapping(Expanded);
+ expandPresetsSpaceBeforeParens(Expanded);
+ expandPresetsSpacesInParens(Expanded);
+
+ // These are handled by separate passes.
+ Expanded.InsertBraces = false;
+ Expanded.RemoveBracesLLVM = false;
+ Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
+ Expanded.RemoveSemicolon = false;
+
+ // Make some sanity adjustments.
+ switch (Expanded.RequiresClausePosition) {
+ case FormatStyle::RCPS_SingleLine:
+ case FormatStyle::RCPS_WithPreceding:
+ Expanded.IndentRequiresClause = false;
+ break;
+ default:
+ break;
+ }
+ if (Expanded.BraceWrapping.AfterEnum)
+ Expanded.AllowShortEnumsOnASingleLine = false;
+
+ if (Expanded.DisableFormat)
+ return {tooling::Replacements(), 0};
+ if (isLikelyXml(Code))
+ return {tooling::Replacements(), 0};
+ if (Expanded.isJavaScript() && isMpegTS(Code))
+ return {tooling::Replacements(), 0};
+
+ // JSON only needs the formatting passing.
+ if (Style.isJson()) {
+ std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
+ auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
+ NextStartColumn, LastStartColumn);
+ if (!Env)
+ return {};
+ // Perform the actual formatting pass.
+ tooling::Replacements Replaces =
+ Formatter(*Env, Style, Status).process().first;
+ // add a replacement to remove the "x = " from the result.
+ if (Code.starts_with("x = ")) {
+ Replaces = Replaces.merge(
+ tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
+ }
+ // apply the reformatting changes and the removal of "x = ".
+ if (applyAllReplacements(Code, Replaces))
+ return {Replaces, 0};
+ return {tooling::Replacements(), 0};
+ }
+
+ auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
+ NextStartColumn, LastStartColumn);
+ if (!Env)
+ return {};
+
+ typedef std::function<std::pair<tooling::Replacements, unsigned>(
+ const Environment &)>
+ AnalyzerPass;
+
+ SmallVector<AnalyzerPass, 16> Passes;
+
+ Passes.emplace_back([&](const Environment &Env) {
+ return IntegerLiteralSeparatorFixer().process(Env, Expanded);
+ });
+
+ Passes.emplace_back([&](const Environment &Env) {
+ return NumericLiteralCaseFixer().process(Env, Expanded);
+ });
+
+ if (Style.isCpp()) {
+ if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
+ addQualifierAlignmentFixerPasses(Expanded, Passes);
+
+ if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
+ FormatStyle S = Expanded;
+ S.RemoveParentheses = Style.RemoveParentheses;
+ Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
+ return ParensRemover(Env, S).process(/*SkipAnnotation=*/true);
+ });
+ }
+
+ if (Style.InsertBraces) {
+ FormatStyle S = Expanded;
+ S.InsertBraces = true;
+ Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
+ return BracesInserter(Env, S).process(/*SkipAnnotation=*/true);
+ });
+ }
+
+ if (Style.RemoveBracesLLVM) {
+ FormatStyle S = Expanded;
+ S.RemoveBracesLLVM = true;
+ Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
+ return BracesRemover(Env, S).process(/*SkipAnnotation=*/true);
+ });
+ }
+
+ if (Style.RemoveSemicolon) {
+ FormatStyle S = Expanded;
+ S.RemoveSemicolon = true;
+ Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
+ return SemiRemover(Env, S).process();
+ });
+ }
+
+ if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return EnumTrailingCommaEditor(Env, Expanded)
+ .process(/*SkipAnnotation=*/true);
+ });
+ }
+
+ if (Style.FixNamespaceComments) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return NamespaceEndCommentsFixer(Env, Expanded).process();
+ });
+ }
+
+ if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return UsingDeclarationsSorter(Env, Expanded).process();
+ });
+ }
+ }
+
+ if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return DefinitionBlockSeparator(Env, Expanded).process();
+ });
+ }
+
+ if (Style.Language == FormatStyle::LK_ObjC &&
+ !Style.ObjCPropertyAttributeOrder.empty()) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return ObjCPropertyAttributeOrderFixer(Env, Expanded).process();
+ });
+ }
+
+ if (Style.isJavaScript() &&
+ Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return JavaScriptRequoter(Env, Expanded).process(/*SkipAnnotation=*/true);
+ });
+ }
+
+ Passes.emplace_back([&](const Environment &Env) {
+ return Formatter(Env, Expanded, Status).process();
+ });
+
+ if (Style.isJavaScript() &&
+ Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return TrailingCommaInserter(Env, Expanded).process();
+ });
+ }
+
+ std::optional<std::string> CurrentCode;
+ tooling::Replacements Fixes;
+ unsigned Penalty = 0;
+ for (size_t I = 0, E = Passes.size(); I < E; ++I) {
+ std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
+ auto NewCode = applyAllReplacements(
+ CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
+ if (NewCode) {
+ Fixes = Fixes.merge(PassFixes.first);
+ Penalty += PassFixes.second;
+ if (I + 1 < E) {
+ CurrentCode = std::move(*NewCode);
+ Env = Environment::make(
+ *CurrentCode, FileName,
+ tooling::calculateRangesAfterReplacements(Fixes, Ranges),
+ FirstStartColumn, NextStartColumn, LastStartColumn);
+ if (!Env)
+ return {};
+ }
+ }
+ }
+
+ if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
+ // Don't make replacements that replace nothing. QualifierAlignment can
+ // produce them if one of its early passes changes e.g. `const volatile` to
+ // `volatile const` and then a later pass changes it back again.
+ tooling::Replacements NonNoOpFixes;
+ for (const tooling::Replacement &Fix : Fixes) {
+ StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
+ if (OriginalCode != Fix.getReplacementText()) {
+ auto Err = NonNoOpFixes.add(Fix);
+ if (Err) {
+ llvm::errs() << "Error adding replacements : "
+ << toString(std::move(Err)) << "\n";
+ }
+ }
+ }
+ Fixes = std::move(NonNoOpFixes);
+ }
+
+ return {Fixes, Penalty};
+}
+} // namespace internal
+
+tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName,
+ FormattingAttemptStatus *Status) {
+ return internal::reformat(Style, Code, Ranges,
+ /*FirstStartColumn=*/0,
+ /*NextStartColumn=*/0,
+ /*LastStartColumn=*/0, FileName, Status)
+ .first;
+}
+
+tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName) {
+ // cleanups only apply to C++ (they mostly concern ctor commas etc.)
+ if (Style.Language != FormatStyle::LK_Cpp)
+ return tooling::Replacements();
+ auto Env = Environment::make(Code, FileName, Ranges);
+ if (!Env)
+ return {};
+ return Cleaner(*Env, Style).process().first;
+}
+
+tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName, bool *IncompleteFormat) {
+ FormattingAttemptStatus Status;
+ auto Result = reformat(Style, Code, Ranges, FileName, &Status);
+ if (!Status.FormatComplete)
+ *IncompleteFormat = true;
+ return Result;
+}
+
+tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
+ StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName) {
+ auto Env = Environment::make(Code, FileName, Ranges);
+ if (!Env)
+ return {};
+ return NamespaceEndCommentsFixer(*Env, Style).process().first;
+}
+
+tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
+ StringRef Code,
+ ArrayRef<tooling::Range> Ranges,
+ StringRef FileName) {
+ auto Env = Environment::make(Code, FileName, Ranges);
+ if (!Env)
+ return {};
+ return UsingDeclarationsSorter(*Env, Style).process().first;
+}
+
+LangOptions getFormattingLangOpts(const FormatStyle &Style) {
+ LangOptions LangOpts;
+
+ auto LexingStd = Style.Standard;
+ if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
+ LexingStd = FormatStyle::LS_Cpp20;
+
+ const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
+ const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
+
+ switch (Style.Language) {
+ case FormatStyle::LK_C:
+ LangOpts.C11 = 1;
+ LangOpts.C23 = 1;
+ break;
+ case FormatStyle::LK_Cpp:
+ case FormatStyle::LK_ObjC:
+ LangOpts.CXXOperatorNames = 1;
+ LangOpts.CPlusPlus11 = SinceCpp11;
+ LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
+ LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
+ LangOpts.CPlusPlus20 = SinceCpp20;
+ [[fallthrough]];
+ default:
+ LangOpts.CPlusPlus = 1;
+ }
+
+ LangOpts.Char8 = SinceCpp20;
+ LangOpts.AllowLiteralDigitSeparator = LangOpts.CPlusPlus14 || LangOpts.C23;
+ // Turning on digraphs in standards before C++0x is error-prone, because e.g.
+ // the sequence "<::" will be unconditionally treated as "[:".
+ // Cf. Lexer::LexTokenInternal.
+ LangOpts.Digraphs = SinceCpp11;
+
+ LangOpts.LineComment = 1;
+ LangOpts.Bool = 1;
+ LangOpts.ObjC = 1;
+ LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
+ LangOpts.DeclSpecKeyword = 1; // To get __declspec.
+ LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
+
+ return LangOpts;
+}
+
+const char *StyleOptionHelpDescription =
+ "Set coding style. <string> can be:\n"
+ "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
+ " Mozilla, WebKit.\n"
+ "2. 'file' to load style configuration from a\n"
+ " .clang-format file in one of the parent directories\n"
+ " of the source file (for stdin, see --assume-filename).\n"
+ " If no .clang-format file is found, falls back to\n"
+ " --fallback-style.\n"
+ " --style=file is the default.\n"
+ "3. 'file:<format_file_path>' to explicitly specify\n"
+ " the configuration file.\n"
+ "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
+ " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
+
+static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
+ if (FileName.ends_with(".c"))
+ return FormatStyle::LK_C;
+ if (FileName.ends_with(".java"))
+ return FormatStyle::LK_Java;
+ if (FileName.ends_with_insensitive(".js") ||
+ FileName.ends_with_insensitive(".mjs") ||
+ FileName.ends_with_insensitive(".cjs") ||
+ FileName.ends_with_insensitive(".ts")) {
+ return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
+ }
+ if (FileName.ends_with(".m") || FileName.ends_with(".mm"))
+ return FormatStyle::LK_ObjC;
+ if (FileName.ends_with_insensitive(".proto") ||
+ FileName.ends_with_insensitive(".protodevel")) {
+ return FormatStyle::LK_Proto;
+ }
+ // txtpb is the canonical extension, and textproto is the legacy canonical
+ // extension
+ // https://protobuf.dev/reference/protobuf/textformat-spec/#text-format-files
+ if (FileName.ends_with_insensitive(".txtpb") ||
+ FileName.ends_with_insensitive(".textpb") ||
+ FileName.ends_with_insensitive(".pb.txt") ||
+ FileName.ends_with_insensitive(".textproto") ||
+ FileName.ends_with_insensitive(".asciipb")) {
+ return FormatStyle::LK_TextProto;
+ }
+ if (FileName.ends_with_insensitive(".td"))
+ return FormatStyle::LK_TableGen;
+ if (FileName.ends_with_insensitive(".cs"))
+ return FormatStyle::LK_CSharp;
+ if (FileName.ends_with_insensitive(".json") ||
+ FileName.ends_with_insensitive(".ipynb")) {
+ return FormatStyle::LK_Json;
+ }
+ if (FileName.ends_with_insensitive(".sv") ||
+ FileName.ends_with_insensitive(".svh") ||
+ FileName.ends_with_insensitive(".v") ||
+ FileName.ends_with_insensitive(".vh")) {
+ return FormatStyle::LK_Verilog;
+ }
+ return FormatStyle::LK_Cpp;
+}
+
+static FormatStyle::LanguageKind getLanguageByComment(const Environment &Env) {
+ const auto ID = Env.getFileID();
+ const auto &SourceMgr = Env.getSourceManager();
+
+ LangOptions LangOpts;
+ LangOpts.CPlusPlus = 1;
+ LangOpts.LineComment = 1;
+
+ Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
+ Lex.SetCommentRetentionState(true);
+
+ for (Token Tok; !Lex.LexFromRawLexer(Tok) && Tok.is(tok::comment);) {
+ auto Text = StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
+ Tok.getLength());
+ if (!Text.consume_front("// clang-format Language:"))
+ continue;
+
+ Text = Text.trim();
+ if (Text == "C")
+ return FormatStyle::LK_C;
+ if (Text == "Cpp")
+ return FormatStyle::LK_Cpp;
+ if (Text == "ObjC")
+ return FormatStyle::LK_ObjC;
+ }
+
+ return FormatStyle::LK_None;
+}
+
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
+ const auto GuessedLanguage = getLanguageByFileName(FileName);
+ if (GuessedLanguage == FormatStyle::LK_Cpp) {
+ auto Extension = llvm::sys::path::extension(FileName);
+ // If there's no file extension (or it's .h), we need to check the contents
+ // of the code to see if it contains Objective-C.
+ if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
+ auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
+ Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
+ if (const auto Language = getLanguageByComment(Env);
+ Language != FormatStyle::LK_None) {
+ return Language;
+ }
+ ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
+ Guesser.process();
+ if (Guesser.isObjC())
+ return FormatStyle::LK_ObjC;
+ }
+ }
+ return GuessedLanguage;
+}
+
+// Update StyleOptionHelpDescription above when changing this.
+const char *DefaultFormatStyle = "file";
+
+const char *DefaultFallbackStyle = "LLVM";
+
+llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
+loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
+ FormatStyle *Style, bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler,
+ bool IsDotHFile) {
+ llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
+ FS->getBufferForFile(ConfigFile.str());
+ if (auto EC = Text.getError())
+ return EC;
+ if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+ DiagHandler, /*DiagHandlerCtx=*/nullptr,
+ IsDotHFile)) {
+ return EC;
+ }
+ return Text;
+}
+
+Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
+ StringRef FallbackStyleName, StringRef Code,
+ llvm::vfs::FileSystem *FS,
+ bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler) {
+ FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
+ FormatStyle FallbackStyle = getNoStyle();
+ if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
+ return make_string_error("Invalid fallback style: " + FallbackStyleName);
+
+ SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1> ChildFormatTextToApply;
+
+ if (StyleName.starts_with("{")) {
+ // Parse YAML/JSON style from the command line.
+ StringRef Source = "<command-line>";
+ if (std::error_code ec =
+ parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
+ AllowUnknownOptions, DiagHandler)) {
+ return make_string_error("Error parsing -style: " + ec.message());
+ }
+
+ if (Style.InheritConfig.empty())
+ return Style;
+
+ ChildFormatTextToApply.emplace_back(
+ llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
+ }
+
+ if (!FS)
+ FS = llvm::vfs::getRealFileSystem().get();
+ assert(FS);
+
+ const bool IsDotHFile = FileName.ends_with(".h");
+
+ // User provided clang-format file using -style=file:path/to/format/file.
+ if (Style.InheritConfig.empty() &&
+ StyleName.starts_with_insensitive("file:")) {
+ auto ConfigFile = StyleName.substr(5);
+ llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
+ loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
+ DiagHandler, IsDotHFile);
+ if (auto EC = Text.getError()) {
+ return make_string_error("Error reading " + ConfigFile + ": " +
+ EC.message());
+ }
+
+ LLVM_DEBUG(llvm::dbgs()
+ << "Using configuration file " << ConfigFile << "\n");
+
+ if (Style.InheritConfig.empty())
+ return Style;
+
+ // Search for parent configs starting from the parent directory of
+ // ConfigFile.
+ FileName = ConfigFile;
+ ChildFormatTextToApply.emplace_back(std::move(*Text));
+ }
+
+ // If the style inherits the parent configuration it is a command line
+ // configuration, which wants to inherit, so we have to skip the check of the
+ // StyleName.
+ if (Style.InheritConfig.empty() && !StyleName.equals_insensitive("file")) {
+ if (!getPredefinedStyle(StyleName, Style.Language, &Style))
+ return make_string_error("Invalid value for -style");
+ if (Style.InheritConfig.empty())
+ return Style;
+ }
+
+ using namespace llvm::sys::path;
+ using String = SmallString<128>;
+
+ String Path(FileName);
+ if (std::error_code EC = FS->makeAbsolute(Path))
+ return make_string_error(EC.message());
+
+ auto Normalize = [](String &Path) {
+ Path = convert_to_slash(Path);
+ remove_dots(Path, /*remove_dot_dot=*/true, Style::posix);
+ };
+
+ Normalize(Path);
+
+ // Reset possible inheritance
+ Style.InheritConfig.clear();
+
+ auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
+
+ auto applyChildFormatTexts = [&](FormatStyle *Style) {
+ for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
+ auto EC =
+ parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+ DiagHandler ? DiagHandler : dropDiagnosticHandler);
+ // It was already correctly parsed.
+ assert(!EC);
+ static_cast<void>(EC);
+ }
+ };
+
+ // Look for .clang-format/_clang-format file in the file's parent directories.
+ SmallVector<std::string, 2> FilesToLookFor;
+ FilesToLookFor.push_back(".clang-format");
+ FilesToLookFor.push_back("_clang-format");
+
+ llvm::StringSet<> Directories; // Inherited directories.
+ bool Redirected = false;
+ String Dir, UnsuitableConfigFiles;
+ for (StringRef Directory = Path; !Directory.empty();
+ Directory = Redirected ? Dir.str() : parent_path(Directory)) {
+ auto Status = FS->status(Directory);
+ if (!Status ||
+ Status->getType() != llvm::sys::fs::file_type::directory_file) {
+ if (!Redirected)
+ continue;
+ return make_string_error("Failed to inherit configuration directory " +
+ Directory);
+ }
+
+ for (const auto &F : FilesToLookFor) {
+ String ConfigFile(Directory);
+
+ append(ConfigFile, F);
+ LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
+ Status = FS->status(ConfigFile);
+ if (!Status ||
+ Status->getType() != llvm::sys::fs::file_type::regular_file) {
+ continue;
+ }
+
+ llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
+ loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
+ DiagHandler, IsDotHFile);
+ if (auto EC = Text.getError()) {
+ if (EC != ParseError::Unsuitable) {
+ return make_string_error("Error reading " + ConfigFile + ": " +
+ EC.message());
+ }
+ if (!UnsuitableConfigFiles.empty())
+ UnsuitableConfigFiles.append(", ");
+ UnsuitableConfigFiles.append(ConfigFile);
+ continue;
+ }
+
+ LLVM_DEBUG(llvm::dbgs()
+ << "Using configuration file " << ConfigFile << "\n");
+
+ if (Style.InheritConfig.empty()) {
+ if (!ChildFormatTextToApply.empty()) {
+ LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
+ applyChildFormatTexts(&Style);
+ }
+ return Style;
+ }
+
+ if (!Directories.insert(Directory).second) {
+ return make_string_error(
+ "Loop detected when inheriting configuration file in " + Directory);
+ }
+
+ LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
+
+ if (Style.InheritConfig == "..") {
+ Redirected = false;
+ } else {
+ Redirected = true;
+ String ExpandedDir;
+ llvm::sys::fs::expand_tilde(Style.InheritConfig, ExpandedDir);
+ Normalize(ExpandedDir);
+ if (is_absolute(ExpandedDir, Style::posix)) {
+ Dir = ExpandedDir;
+ } else {
+ Dir = Directory.str();
+ append(Dir, Style::posix, ExpandedDir);
+ }
+ }
+
+ // Reset inheritance of style
+ Style.InheritConfig.clear();
+
+ ChildFormatTextToApply.emplace_back(std::move(*Text));
+
+ // Breaking out of the inner loop, since we don't want to parse
+ // .clang-format AND _clang-format, if both exist. Then we continue the
+ // outer loop (parent directories) in search for the parent
+ // configuration.
+ break;
+ }
+ }
+
+ if (!UnsuitableConfigFiles.empty()) {
+ return make_string_error("Configuration file(s) do(es) not support " +
+ getLanguageName(Style.Language) + ": " +
+ UnsuitableConfigFiles);
+ }
+
+ if (!ChildFormatTextToApply.empty()) {
+ LLVM_DEBUG(llvm::dbgs()
+ << "Applying child configurations on fallback style\n");
+ applyChildFormatTexts(&FallbackStyle);
+ }
+
+ return FallbackStyle;
+}
+
+static bool isClangFormatOnOff(StringRef Comment, bool On) {
+ if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
+ return true;
+
+ static const char ClangFormatOn[] = "// clang-format on";
+ static const char ClangFormatOff[] = "// clang-format off";
+ const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 1;
+
+ return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
+ (Comment.size() == Size || Comment[Size] == ':');
+}
+
+bool isClangFormatOn(StringRef Comment) {
+ return isClangFormatOnOff(Comment, /*On=*/true);
+}
+
+bool isClangFormatOff(StringRef Comment) {
+ return isClangFormatOnOff(Comment, /*On=*/false);
+}
+
+} // namespace format
+} // namespace clang
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 1ba0d7e891b09..192ec3b58510c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1,6682 +1,6693 @@
-//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-///
-/// \file
-/// This file implements a token annotator, i.e. creates
-/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
-///
-//===----------------------------------------------------------------------===//
-
-#include "TokenAnnotator.h"
-#include "FormatToken.h"
-#include "clang/Basic/TokenKinds.h"
-#include "llvm/ADT/SmallPtrSet.h"
-#include "llvm/Support/Debug.h"
-
-#define DEBUG_TYPE "format-token-annotator"
-
-namespace clang {
-namespace format {
-
-static bool mustBreakAfterAttributes(const FormatToken &Tok,
- const FormatStyle &Style) {
- switch (Style.BreakAfterAttributes) {
- case FormatStyle::ABS_Always:
- return true;
- case FormatStyle::ABS_Never:
- return false;
- default: // ABS_Leave and ABS_LeaveAll
- return Tok.NewlinesBefore > 0;
- }
-}
-
-namespace {
-
-/// Returns \c true if the line starts with a token that can start a statement
-/// with an initializer.
-static bool startsWithInitStatement(const AnnotatedLine &Line) {
- return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
- Line.startsWith(tok::kw_switch);
-}
-
-/// Returns \c true if the token can be used as an identifier in
-/// an Objective-C \c \@selector, \c false otherwise.
-///
-/// Because getFormattingLangOpts() always lexes source code as
-/// Objective-C++, C++ keywords like \c new and \c delete are
-/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
-///
-/// For Objective-C and Objective-C++, both identifiers and keywords
-/// are valid inside @selector(...) (or a macro which
-/// invokes @selector(...)). So, we allow treat any identifier or
-/// keyword as a potential Objective-C selector component.
-static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
- return Tok.Tok.getIdentifierInfo();
-}
-
-/// With `Left` being '(', check if we're at either `[...](` or
-/// `[...]<...>(`, where the [ opens a lambda capture list.
-// FIXME: this doesn't cover attributes/constraints before the l_paren.
-static bool isLambdaParameterList(const FormatToken *Left) {
- // Skip <...> if present.
- if (Left->Previous && Left->Previous->is(tok::greater) &&
- Left->Previous->MatchingParen &&
- Left->Previous->MatchingParen->is(TT_TemplateOpener)) {
- Left = Left->Previous->MatchingParen;
- }
-
- // Check for `[...]`.
- return Left->Previous && Left->Previous->is(tok::r_square) &&
- Left->Previous->MatchingParen &&
- Left->Previous->MatchingParen->is(TT_LambdaLSquare);
-}
-
-/// Returns \c true if the token is followed by a boolean condition, \c false
-/// otherwise.
-static bool isKeywordWithCondition(const FormatToken &Tok) {
- return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
- tok::kw_constexpr, tok::kw_catch);
-}
-
-/// Returns \c true if the token starts a C++ attribute, \c false otherwise.
-static bool isCppAttribute(bool IsCpp, const FormatToken &Tok) {
- if (!IsCpp || !Tok.startsSequence(tok::l_square, tok::l_square))
- return false;
- // The first square bracket is part of an ObjC array literal
- if (Tok.Previous && Tok.Previous->is(tok::at))
- return false;
- const FormatToken *AttrTok = Tok.Next->Next;
- if (!AttrTok)
- return false;
- // C++17 '[[using ns: foo, bar(baz, blech)]]'
- // We assume nobody will name an ObjC variable 'using'.
- if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
- return true;
- if (AttrTok->isNot(tok::identifier))
- return false;
- while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
- // ObjC message send. We assume nobody will use : in a C++11 attribute
- // specifier parameter, although this is technically valid:
- // [[foo(:)]].
- if (AttrTok->is(tok::colon) ||
- AttrTok->startsSequence(tok::identifier, tok::identifier) ||
- AttrTok->startsSequence(tok::r_paren, tok::identifier)) {
- return false;
- }
- if (AttrTok->is(tok::ellipsis))
- return true;
- AttrTok = AttrTok->Next;
- }
- return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
-}
-
-/// A parser that gathers additional information about tokens.
-///
-/// The \c TokenAnnotator tries to match parenthesis and square brakets and
-/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
-/// into template parameter lists.
-class AnnotatingParser {
-public:
- AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
- const AdditionalKeywords &Keywords,
- SmallVector<ScopeType> &Scopes)
- : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
- IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
- Keywords(Keywords), Scopes(Scopes), TemplateDeclarationDepth(0) {
- Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
- resetTokenMetadata();
- }
-
-private:
- ScopeType getScopeType(const FormatToken &Token) const {
- switch (Token.getType()) {
- case TT_ClassLBrace:
- case TT_StructLBrace:
- case TT_UnionLBrace:
- return ST_Class;
- case TT_CompoundRequirementLBrace:
- return ST_CompoundRequirement;
- default:
- return ST_Other;
- }
- }
-
- bool parseAngle() {
- if (!CurrentToken)
- return false;
-
- auto *Left = CurrentToken->Previous; // The '<'.
- if (!Left)
- return false;
-
- if (NonTemplateLess.count(Left) > 0)
- return false;
-
- const auto *BeforeLess = Left->Previous;
-
- if (BeforeLess) {
- if (BeforeLess->Tok.isLiteral())
- return false;
- if (BeforeLess->is(tok::r_brace))
- return false;
- if (BeforeLess->is(tok::r_paren) && Contexts.size() > 1 &&
- !(BeforeLess->MatchingParen &&
- BeforeLess->MatchingParen->is(TT_OverloadedOperatorLParen))) {
- return false;
- }
- if (BeforeLess->is(tok::kw_operator) && CurrentToken->is(tok::l_paren))
- return false;
- }
-
- Left->ParentBracket = Contexts.back().ContextKind;
- ScopedContextCreator ContextCreator(*this, tok::less, 12);
- Contexts.back().IsExpression = false;
-
- // If there's a template keyword before the opening angle bracket, this is a
- // template parameter, not an argument.
- if (BeforeLess && BeforeLess->isNot(tok::kw_template))
- Contexts.back().ContextType = Context::TemplateArgument;
-
- if (Style.isJava() && CurrentToken->is(tok::question))
- next();
-
- for (bool SeenTernaryOperator = false, MaybeAngles = true; CurrentToken;) {
- const auto &ParentContext = Contexts[Contexts.size() - 2];
- const bool InExpr = ParentContext.IsExpression;
- if (CurrentToken->is(tok::greater)) {
- const auto *Next = CurrentToken->Next;
- if (CurrentToken->isNot(TT_TemplateCloser)) {
- // Try to do a better job at looking for ">>" within the condition of
- // a statement. Conservatively insert spaces between consecutive ">"
- // tokens to prevent splitting right shift operators and potentially
- // altering program semantics. This check is overly conservative and
- // will prevent spaces from being inserted in select nested template
- // parameter cases, but should not alter program semantics.
- if (Next && Next->is(tok::greater) &&
- Left->ParentBracket != tok::less &&
- CurrentToken->getStartOfNonWhitespace() ==
- Next->getStartOfNonWhitespace().getLocWithOffset(-1)) {
- return false;
- }
- if (InExpr && SeenTernaryOperator &&
- (!Next || Next->isNoneOf(tok::l_paren, tok::l_brace))) {
- return false;
- }
- if (!MaybeAngles)
- return false;
- if (ParentContext.InStaticAssertFirstArgument && Next &&
- Next->isOneOf(tok::minus, tok::identifier)) {
- return false;
- }
- }
- Left->MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = Left;
- // In TT_Proto, we must distignuish between:
- // map<key, value>
- // msg < item: data >
- // msg: < item: data >
- // In TT_TextProto, map<key, value> does not occur.
- if (Style.isTextProto() ||
- (Style.Language == FormatStyle::LK_Proto && BeforeLess &&
- BeforeLess->isOneOf(TT_SelectorName, TT_DictLiteral))) {
- CurrentToken->setType(TT_DictLiteral);
- } else {
- CurrentToken->setType(TT_TemplateCloser);
- CurrentToken->Tok.setLength(1);
- }
- if (Next && Next->Tok.isLiteral())
- return false;
- next();
- return true;
- }
- if (BeforeLess && BeforeLess->is(TT_TemplateName)) {
- next();
- continue;
- }
- if (CurrentToken->is(tok::question) && Style.isJava()) {
- next();
- continue;
- }
- if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
- return false;
- const auto &Prev = *CurrentToken->Previous;
- // If a && or || is found and interpreted as a binary operator, this set
- // of angles is likely part of something like "a < b && c > d". If the
- // angles are inside an expression, the ||/&& might also be a binary
- // operator that was misinterpreted because we are parsing template
- // parameters.
- // FIXME: This is getting out of hand, write a decent parser.
- if (MaybeAngles && InExpr && !Line.startsWith(tok::kw_template) &&
- Prev.is(TT_BinaryOperator) &&
- Prev.isOneOf(tok::pipepipe, tok::ampamp)) {
- MaybeAngles = false;
- }
- if (Prev.isOneOf(tok::question, tok::colon) && !Style.isProto())
- SeenTernaryOperator = true;
- updateParameterCount(Left, CurrentToken);
- if (Style.Language == FormatStyle::LK_Proto) {
- if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
- if (CurrentToken->is(tok::colon) ||
- (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
- Previous->isNot(tok::colon))) {
- Previous->setType(TT_SelectorName);
- }
- }
- } else if (Style.isTableGen()) {
- if (CurrentToken->isOneOf(tok::comma, tok::equal)) {
- // They appear as separators. Unless they are not in class definition.
- next();
- continue;
- }
- // In angle, there must be Value like tokens. Types are also able to be
- // parsed in the same way with Values.
- if (!parseTableGenValue())
- return false;
- continue;
- }
- if (!consumeToken())
- return false;
- }
- return false;
- }
-
- bool parseUntouchableParens() {
- while (CurrentToken) {
- CurrentToken->Finalized = true;
- switch (CurrentToken->Tok.getKind()) {
- case tok::l_paren:
- next();
- if (!parseUntouchableParens())
- return false;
- continue;
- case tok::r_paren:
- next();
- return true;
- default:
- // no-op
- break;
- }
- next();
- }
- return false;
- }
-
- bool parseParens(bool IsIf = false) {
- if (!CurrentToken)
- return false;
- assert(CurrentToken->Previous && "Unknown previous token");
- FormatToken &OpeningParen = *CurrentToken->Previous;
- assert(OpeningParen.is(tok::l_paren));
- FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
- OpeningParen.ParentBracket = Contexts.back().ContextKind;
- ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
-
- // FIXME: This is a bit of a hack. Do better.
- Contexts.back().ColonIsForRangeExpr =
- Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
-
- if (OpeningParen.Previous &&
- OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
- OpeningParen.Finalized = true;
- return parseUntouchableParens();
- }
-
- bool StartsObjCSelector = false;
- if (!Style.isVerilog()) {
- if (FormatToken *MaybeSel = OpeningParen.Previous) {
- // @selector( starts a selector.
- if (MaybeSel->is(tok::objc_selector) && MaybeSel->Previous &&
- MaybeSel->Previous->is(tok::at)) {
- StartsObjCSelector = true;
- }
- }
- }
-
- if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
- // Find the previous kw_operator token.
- FormatToken *Prev = &OpeningParen;
- while (Prev->isNot(tok::kw_operator)) {
- Prev = Prev->Previous;
- assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
- }
-
- // If faced with "a.operator*(argument)" or "a->operator*(argument)",
- // i.e. the operator is called as a member function,
- // then the argument must be an expression.
- bool OperatorCalledAsMemberFunction =
- Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
- Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
- } else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
- Contexts.back().IsExpression = true;
- Contexts.back().ContextType = Context::VerilogInstancePortList;
- } else if (Style.isJavaScript() &&
- (Line.startsWith(Keywords.kw_type, tok::identifier) ||
- Line.startsWith(tok::kw_export, Keywords.kw_type,
- tok::identifier))) {
- // type X = (...);
- // export type X = (...);
- Contexts.back().IsExpression = false;
- } else if (OpeningParen.Previous &&
- (OpeningParen.Previous->isOneOf(
- tok::kw_noexcept, tok::kw_explicit, tok::kw_while,
- tok::l_paren, tok::comma, TT_CastRParen,
- TT_BinaryOperator) ||
- OpeningParen.Previous->isIf())) {
- // if and while usually contain expressions.
- Contexts.back().IsExpression = true;
- } else if (Style.isJavaScript() && OpeningParen.Previous &&
- (OpeningParen.Previous->is(Keywords.kw_function) ||
- (OpeningParen.Previous->endsSequence(tok::identifier,
- Keywords.kw_function)))) {
- // function(...) or function f(...)
- Contexts.back().IsExpression = false;
- } else if (Style.isJavaScript() && OpeningParen.Previous &&
- OpeningParen.Previous->is(TT_JsTypeColon)) {
- // let x: (SomeType);
- Contexts.back().IsExpression = false;
- } else if (isLambdaParameterList(&OpeningParen)) {
- // This is a parameter list of a lambda expression.
- OpeningParen.setType(TT_LambdaDefinitionLParen);
- Contexts.back().IsExpression = false;
- } else if (OpeningParen.is(TT_RequiresExpressionLParen)) {
- Contexts.back().IsExpression = false;
- } else if (OpeningParen.Previous &&
- OpeningParen.Previous->is(tok::kw__Generic)) {
- Contexts.back().ContextType = Context::C11GenericSelection;
- Contexts.back().IsExpression = true;
- } else if (OpeningParen.Previous &&
- OpeningParen.Previous->TokenText == "Q_PROPERTY") {
- Contexts.back().ContextType = Context::QtProperty;
- Contexts.back().IsExpression = false;
- } else if (Line.InPPDirective &&
- (!OpeningParen.Previous ||
- OpeningParen.Previous->isNot(tok::identifier))) {
- Contexts.back().IsExpression = true;
- } else if (Contexts[Contexts.size() - 2].CaretFound) {
- // This is the parameter list of an ObjC block.
- Contexts.back().IsExpression = false;
- } else if (OpeningParen.Previous &&
- OpeningParen.Previous->is(TT_ForEachMacro)) {
- // The first argument to a foreach macro is a declaration.
- Contexts.back().ContextType = Context::ForEachMacro;
- Contexts.back().IsExpression = false;
- } else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen &&
- OpeningParen.Previous->MatchingParen->isOneOf(
- TT_ObjCBlockLParen, TT_FunctionTypeLParen)) {
- Contexts.back().IsExpression = false;
- } else if (!Line.MustBeDeclaration &&
- (!Line.InPPDirective || (Line.InMacroBody && !Scopes.empty()))) {
- bool IsForOrCatch =
- OpeningParen.Previous &&
- OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch);
- Contexts.back().IsExpression = !IsForOrCatch;
- }
-
- if (Style.isTableGen()) {
- if (FormatToken *Prev = OpeningParen.Previous) {
- if (Prev->is(TT_TableGenCondOperator)) {
- Contexts.back().IsTableGenCondOpe = true;
- Contexts.back().IsExpression = true;
- } else if (Contexts.size() > 1 &&
- Contexts[Contexts.size() - 2].IsTableGenBangOpe) {
- // Hack to handle bang operators. The parent context's flag
- // was set by parseTableGenSimpleValue().
- // We have to specify the context outside because the prev of "(" may
- // be ">", not the bang operator in this case.
- Contexts.back().IsTableGenBangOpe = true;
- Contexts.back().IsExpression = true;
- } else {
- // Otherwise, this paren seems DAGArg.
- if (!parseTableGenDAGArg())
- return false;
- return parseTableGenDAGArgAndList(&OpeningParen);
- }
- }
- }
-
- // Infer the role of the l_paren based on the previous token if we haven't
- // detected one yet.
- if (PrevNonComment && OpeningParen.is(TT_Unknown)) {
- if (PrevNonComment->isAttribute()) {
- OpeningParen.setType(TT_AttributeLParen);
- } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
- tok::kw_typeof,
-#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
-#include "clang/Basic/TransformTypeTraits.def"
- tok::kw__Atomic)) {
- OpeningParen.setType(TT_TypeDeclarationParen);
- // decltype() and typeof() usually contain expressions.
- if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
- Contexts.back().IsExpression = true;
- }
- }
-
- if (StartsObjCSelector)
- OpeningParen.setType(TT_ObjCSelector);
-
- const bool IsStaticAssert =
- PrevNonComment && PrevNonComment->is(tok::kw_static_assert);
- if (IsStaticAssert)
- Contexts.back().InStaticAssertFirstArgument = true;
-
- // MightBeFunctionType and ProbablyFunctionType are used for
- // function pointer and reference types as well as Objective-C
- // block types:
- //
- // void (*FunctionPointer)(void);
- // void (&FunctionReference)(void);
- // void (&&FunctionReference)(void);
- // void (^ObjCBlock)(void);
- bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
- bool ProbablyFunctionType =
- CurrentToken->isPointerOrReference() || CurrentToken->is(tok::caret);
- bool HasMultipleLines = false;
- bool HasMultipleParametersOnALine = false;
- bool MightBeObjCForRangeLoop =
- OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for);
- FormatToken *PossibleObjCForInToken = nullptr;
- while (CurrentToken) {
- const auto &Prev = *CurrentToken->Previous;
- const auto *PrevPrev = Prev.Previous;
- if (Prev.is(TT_PointerOrReference) &&
- PrevPrev->isOneOf(tok::l_paren, tok::coloncolon)) {
- ProbablyFunctionType = true;
- }
- if (CurrentToken->is(tok::comma))
- MightBeFunctionType = false;
- if (Prev.is(TT_BinaryOperator))
- Contexts.back().IsExpression = true;
- if (CurrentToken->is(tok::r_paren)) {
- if (Prev.is(TT_PointerOrReference) &&
- (PrevPrev == &OpeningParen || PrevPrev->is(tok::coloncolon))) {
- MightBeFunctionType = true;
- }
- if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType &&
- ProbablyFunctionType && CurrentToken->Next &&
- (CurrentToken->Next->is(tok::l_paren) ||
- (CurrentToken->Next->is(tok::l_square) &&
- (Line.MustBeDeclaration ||
- (PrevNonComment && PrevNonComment->isTypeName(LangOpts)))))) {
- OpeningParen.setType(OpeningParen.Next->is(tok::caret)
- ? TT_ObjCBlockLParen
- : TT_FunctionTypeLParen);
- }
- OpeningParen.MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = &OpeningParen;
-
- if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
- OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) {
- // Detect the case where macros are used to generate lambdas or
- // function bodies, e.g.:
- // auto my_lambda = MACRO((Type *type, int i) { .. body .. });
- for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
- Tok = Tok->Next) {
- if (Tok->is(TT_BinaryOperator) && Tok->isPointerOrReference())
- Tok->setType(TT_PointerOrReference);
- }
- }
-
- if (StartsObjCSelector) {
- CurrentToken->setType(TT_ObjCSelector);
- if (Contexts.back().FirstObjCSelectorName) {
- Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
- Contexts.back().LongestObjCSelectorName;
- }
- }
-
- if (OpeningParen.is(TT_AttributeLParen))
- CurrentToken->setType(TT_AttributeRParen);
- if (OpeningParen.is(TT_TypeDeclarationParen))
- CurrentToken->setType(TT_TypeDeclarationParen);
- if (OpeningParen.Previous &&
- OpeningParen.Previous->is(TT_JavaAnnotation)) {
- CurrentToken->setType(TT_JavaAnnotation);
- }
- if (OpeningParen.Previous &&
- OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) {
- CurrentToken->setType(TT_LeadingJavaAnnotation);
- }
-
- if (!HasMultipleLines)
- OpeningParen.setPackingKind(PPK_Inconclusive);
- else if (HasMultipleParametersOnALine)
- OpeningParen.setPackingKind(PPK_BinPacked);
- else
- OpeningParen.setPackingKind(PPK_OnePerLine);
-
- next();
- return true;
- }
- if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
- return false;
-
- if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen))
- OpeningParen.setType(TT_Unknown);
- if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
- !CurrentToken->Next->HasUnescapedNewline &&
- !CurrentToken->Next->isTrailingComment()) {
- HasMultipleParametersOnALine = true;
- }
- bool ProbablyFunctionTypeLParen =
- (CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
- CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
- if ((Prev.isOneOf(tok::kw_const, tok::kw_auto) ||
- Prev.isTypeName(LangOpts)) &&
- !(CurrentToken->is(tok::l_brace) ||
- (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) {
- Contexts.back().IsExpression = false;
- }
- if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
- MightBeObjCForRangeLoop = false;
- if (PossibleObjCForInToken) {
- PossibleObjCForInToken->setType(TT_Unknown);
- PossibleObjCForInToken = nullptr;
- }
- }
- if (IsIf && CurrentToken->is(tok::semi)) {
- for (auto *Tok = OpeningParen.Next;
- Tok != CurrentToken &&
- Tok->isNoneOf(tok::equal, tok::l_paren, tok::l_brace);
- Tok = Tok->Next) {
- if (Tok->isPointerOrReference())
- Tok->setFinalizedType(TT_PointerOrReference);
- }
- }
- if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
- PossibleObjCForInToken = CurrentToken;
- PossibleObjCForInToken->setType(TT_ObjCForIn);
- }
- // When we discover a 'new', we set CanBeExpression to 'false' in order to
- // parse the type correctly. Reset that after a comma.
- if (CurrentToken->is(tok::comma)) {
- if (IsStaticAssert)
- Contexts.back().InStaticAssertFirstArgument = false;
- else
- Contexts.back().CanBeExpression = true;
- }
-
- if (Style.isTableGen()) {
- if (CurrentToken->is(tok::comma)) {
- if (Contexts.back().IsTableGenCondOpe)
- CurrentToken->setType(TT_TableGenCondOperatorComma);
- next();
- } else if (CurrentToken->is(tok::colon)) {
- if (Contexts.back().IsTableGenCondOpe)
- CurrentToken->setType(TT_TableGenCondOperatorColon);
- next();
- }
- // In TableGen there must be Values in parens.
- if (!parseTableGenValue())
- return false;
- continue;
- }
-
- FormatToken *Tok = CurrentToken;
- if (!consumeToken())
- return false;
- updateParameterCount(&OpeningParen, Tok);
- if (CurrentToken && CurrentToken->HasUnescapedNewline)
- HasMultipleLines = true;
- }
- return false;
- }
-
- bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
- if (!Style.isCSharp())
- return false;
-
- // `identifier[i]` is not an attribute.
- if (Tok.Previous && Tok.Previous->is(tok::identifier))
- return false;
-
- // Chains of [] in `identifier[i][j][k]` are not attributes.
- if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
- auto *MatchingParen = Tok.Previous->MatchingParen;
- if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
- return false;
- }
-
- const FormatToken *AttrTok = Tok.Next;
- if (!AttrTok)
- return false;
-
- // Just an empty declaration e.g. string [].
- if (AttrTok->is(tok::r_square))
- return false;
-
- // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
- while (AttrTok && AttrTok->isNot(tok::r_square))
- AttrTok = AttrTok->Next;
-
- if (!AttrTok)
- return false;
-
- // Allow an attribute to be the only content of a file.
- AttrTok = AttrTok->Next;
- if (!AttrTok)
- return true;
-
- // Limit this to being an access modifier that follows.
- if (AttrTok->isAccessSpecifierKeyword() ||
- AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
- tok::l_square, Keywords.kw_internal)) {
- return true;
- }
-
- // incase its a [XXX] retval func(....
- if (AttrTok->Next &&
- AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) {
- return true;
- }
-
- return false;
- }
-
- bool parseSquare() {
- if (!CurrentToken)
- return false;
-
- // A '[' could be an index subscript (after an identifier or after
- // ')' or ']'), it could be the start of an Objective-C method
- // expression, it could the start of an Objective-C array literal,
- // or it could be a C++ attribute specifier [[foo::bar]].
- FormatToken *Left = CurrentToken->Previous;
- Left->ParentBracket = Contexts.back().ContextKind;
- FormatToken *Parent = Left->getPreviousNonComment();
-
- // Cases where '>' is followed by '['.
- // In C++, this can happen either in array of templates (foo<int>[10])
- // or when array is a nested template type (unique_ptr<type1<type2>[]>).
- bool CppArrayTemplates =
- IsCpp && Parent && Parent->is(TT_TemplateCloser) &&
- (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
- Contexts.back().ContextType == Context::TemplateArgument);
-
- const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
- const bool IsCpp11AttributeSpecifier =
- isCppAttribute(IsCpp, *Left) || IsInnerSquare;
-
- // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
- bool IsCSharpAttributeSpecifier =
- isCSharpAttributeSpecifier(*Left) ||
- Contexts.back().InCSharpAttributeSpecifier;
-
- bool InsideInlineASM = Line.startsWith(tok::kw_asm);
- bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
- bool StartsObjCMethodExpr =
- !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
- IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
- Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
- CurrentToken->isNoneOf(tok::l_brace, tok::r_square) &&
- // Do not consider '[' after a comma inside a braced initializer the
- // start of an ObjC method expression. In braced initializer lists,
- // commas are list separators and should not trigger ObjC parsing.
- (!Parent || !Parent->is(tok::comma) ||
- Contexts.back().ContextKind != tok::l_brace) &&
- (!Parent ||
- Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
- tok::kw_return, tok::kw_throw) ||
- Parent->isUnaryOperator() ||
- // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
- Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
- (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
- prec::Unknown));
- bool ColonFound = false;
-
- unsigned BindingIncrease = 1;
- if (IsCppStructuredBinding) {
- Left->setType(TT_StructuredBindingLSquare);
- } else if (Left->is(TT_Unknown)) {
- if (StartsObjCMethodExpr) {
- Left->setType(TT_ObjCMethodExpr);
- } else if (InsideInlineASM) {
- Left->setType(TT_InlineASMSymbolicNameLSquare);
- } else if (IsCpp11AttributeSpecifier) {
- if (!IsInnerSquare) {
- Left->setType(TT_AttributeLSquare);
- if (Left->Previous)
- Left->Previous->EndsCppAttributeGroup = false;
- }
- } else if (Style.isJavaScript() && Parent &&
- Contexts.back().ContextKind == tok::l_brace &&
- Parent->isOneOf(tok::l_brace, tok::comma)) {
- Left->setType(TT_JsComputedPropertyName);
- } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
- Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
- Left->setType(TT_DesignatedInitializerLSquare);
- } else if (IsCSharpAttributeSpecifier) {
- Left->setType(TT_AttributeLSquare);
- } else if (CurrentToken->is(tok::r_square) && Parent &&
- Parent->is(TT_TemplateCloser)) {
- Left->setType(TT_ArraySubscriptLSquare);
- } else if (Style.isProto()) {
- // Square braces in LK_Proto can either be message field attributes:
- //
- // optional Aaa aaa = 1 [
- // (aaa) = aaa
- // ];
- //
- // extensions 123 [
- // (aaa) = aaa
- // ];
- //
- // or text proto extensions (in options):
- //
- // option (Aaa.options) = {
- // [type.type/type] {
- // key: value
- // }
- // }
- //
- // or repeated fields (in options):
- //
- // option (Aaa.options) = {
- // keys: [ 1, 2, 3 ]
- // }
- //
- // In the first and the third case we want to spread the contents inside
- // the square braces; in the second we want to keep them inline.
- Left->setType(TT_ArrayInitializerLSquare);
- if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
- tok::equal) &&
- !Left->endsSequence(tok::l_square, tok::numeric_constant,
- tok::identifier) &&
- !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
- Left->setType(TT_ProtoExtensionLSquare);
- BindingIncrease = 10;
- }
- } else if (!CppArrayTemplates && Parent &&
- Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
- tok::comma, tok::l_paren, tok::l_square,
- tok::question, tok::colon, tok::kw_return,
- // Should only be relevant to JavaScript:
- tok::kw_default)) {
- Left->setType(TT_ArrayInitializerLSquare);
- } else {
- BindingIncrease = 10;
- Left->setType(TT_ArraySubscriptLSquare);
- }
- }
-
- ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
- Contexts.back().IsExpression = true;
- if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon))
- Contexts.back().IsExpression = false;
-
- Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
- Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
- Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
-
- while (CurrentToken) {
- if (CurrentToken->is(tok::r_square)) {
- if (IsCpp11AttributeSpecifier && !IsInnerSquare) {
- CurrentToken->setType(TT_AttributeRSquare);
- CurrentToken->EndsCppAttributeGroup = true;
- }
- if (IsCSharpAttributeSpecifier) {
- CurrentToken->setType(TT_AttributeRSquare);
- } else if (((CurrentToken->Next &&
- CurrentToken->Next->is(tok::l_paren)) ||
- (CurrentToken->Previous &&
- CurrentToken->Previous->Previous == Left)) &&
- Left->is(TT_ObjCMethodExpr)) {
- // An ObjC method call is rarely followed by an open parenthesis. It
- // also can't be composed of just one token, unless it's a macro that
- // will be expanded to more tokens.
- // FIXME: Do we incorrectly label ":" with this?
- StartsObjCMethodExpr = false;
- Left->setType(TT_Unknown);
- }
- if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
- CurrentToken->setType(TT_ObjCMethodExpr);
- // If we haven't seen a colon yet, make sure the last identifier
- // before the r_square is tagged as a selector name component.
- if (!ColonFound && CurrentToken->Previous &&
- CurrentToken->Previous->is(TT_Unknown) &&
- canBeObjCSelectorComponent(*CurrentToken->Previous)) {
- CurrentToken->Previous->setType(TT_SelectorName);
- }
- // determineStarAmpUsage() thinks that '*' '[' is allocating an
- // array of pointers, but if '[' starts a selector then '*' is a
- // binary operator.
- if (Parent && Parent->is(TT_PointerOrReference))
- Parent->overwriteFixedType(TT_BinaryOperator);
- }
- Left->MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = Left;
- // FirstObjCSelectorName is set when a colon is found. This does
- // not work, however, when the method has no parameters.
- // Here, we set FirstObjCSelectorName when the end of the method call is
- // reached, in case it was not set already.
- if (!Contexts.back().FirstObjCSelectorName) {
- FormatToken *Previous = CurrentToken->getPreviousNonComment();
- if (Previous && Previous->is(TT_SelectorName)) {
- Previous->ObjCSelectorNameParts = 1;
- Contexts.back().FirstObjCSelectorName = Previous;
- }
- } else {
- Left->ParameterCount =
- Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
- }
- if (Contexts.back().FirstObjCSelectorName) {
- Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
- Contexts.back().LongestObjCSelectorName;
- if (Left->BlockParameterCount > 1)
- Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
- }
- if (Style.isTableGen() && Left->is(TT_TableGenListOpener))
- CurrentToken->setType(TT_TableGenListCloser);
- next();
- return true;
- }
- if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
- return false;
- if (CurrentToken->is(tok::colon)) {
- if (IsCpp11AttributeSpecifier &&
- CurrentToken->endsSequence(tok::colon, tok::identifier,
- tok::kw_using)) {
- // Remember that this is a [[using ns: foo]] C++ attribute, so we
- // don't add a space before the colon (unlike other colons).
- CurrentToken->setType(TT_AttributeColon);
- } else if (!Style.isVerilog() && !Line.InPragmaDirective &&
- Left->isOneOf(TT_ArraySubscriptLSquare,
- TT_DesignatedInitializerLSquare)) {
- Left->setType(TT_ObjCMethodExpr);
- StartsObjCMethodExpr = true;
- Contexts.back().ColonIsObjCMethodExpr = true;
- if (Parent && Parent->is(tok::r_paren)) {
- // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
- Parent->setType(TT_CastRParen);
- }
- }
- ColonFound = true;
- }
- if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
- !ColonFound) {
- Left->setType(TT_ArrayInitializerLSquare);
- }
- FormatToken *Tok = CurrentToken;
- if (Style.isTableGen()) {
- if (CurrentToken->isOneOf(tok::comma, tok::minus, tok::ellipsis)) {
- // '-' and '...' appears as a separator in slice.
- next();
- } else {
- // In TableGen there must be a list of Values in square brackets.
- // It must be ValueList or SliceElements.
- if (!parseTableGenValue())
- return false;
- }
- updateParameterCount(Left, Tok);
- continue;
- }
- if (!consumeToken())
- return false;
- updateParameterCount(Left, Tok);
- }
- return false;
- }
-
- void skipToNextNonComment() {
- next();
- while (CurrentToken && CurrentToken->is(tok::comment))
- next();
- }
-
- // Simplified parser for TableGen Value. Returns true on success.
- // It consists of SimpleValues, SimpleValues with Suffixes, and Value followed
- // by '#', paste operator.
- // There also exists the case the Value is parsed as NameValue.
- // In this case, the Value ends if '{' is found.
- bool parseTableGenValue(bool ParseNameMode = false) {
- if (!CurrentToken)
- return false;
- while (CurrentToken->is(tok::comment))
- next();
- if (!parseTableGenSimpleValue())
- return false;
- if (!CurrentToken)
- return true;
- // Value "#" [Value]
- if (CurrentToken->is(tok::hash)) {
- if (CurrentToken->Next &&
- CurrentToken->Next->isOneOf(tok::colon, tok::semi, tok::l_brace)) {
- // Trailing paste operator.
- // These are only the allowed cases in TGParser::ParseValue().
- CurrentToken->setType(TT_TableGenTrailingPasteOperator);
- next();
- return true;
- }
- FormatToken *HashTok = CurrentToken;
- skipToNextNonComment();
- HashTok->setType(TT_Unknown);
- if (!parseTableGenValue(ParseNameMode))
- return false;
- if (!CurrentToken)
- return true;
- }
- // In name mode, '{' is regarded as the end of the value.
- // See TGParser::ParseValue in TGParser.cpp
- if (ParseNameMode && CurrentToken->is(tok::l_brace))
- return true;
- // These tokens indicates this is a value with suffixes.
- if (CurrentToken->isOneOf(tok::l_brace, tok::l_square, tok::period)) {
- CurrentToken->setType(TT_TableGenValueSuffix);
- FormatToken *Suffix = CurrentToken;
- skipToNextNonComment();
- if (Suffix->is(tok::l_square))
- return parseSquare();
- if (Suffix->is(tok::l_brace)) {
- Scopes.push_back(getScopeType(*Suffix));
- return parseBrace();
- }
- }
- return true;
- }
-
- // TokVarName ::= "$" ualpha (ualpha | "0"..."9")*
- // Appears as a part of DagArg.
- // This does not change the current token on fail.
- bool tryToParseTableGenTokVar() {
- if (!CurrentToken)
- return false;
- if (CurrentToken->is(tok::identifier) &&
- CurrentToken->TokenText.front() == '$') {
- skipToNextNonComment();
- return true;
- }
- return false;
- }
-
- // DagArg ::= Value [":" TokVarName] | TokVarName
- // Appears as a part of SimpleValue6.
- bool parseTableGenDAGArg(bool AlignColon = false) {
- if (tryToParseTableGenTokVar())
- return true;
- if (parseTableGenValue()) {
- if (CurrentToken && CurrentToken->is(tok::colon)) {
- if (AlignColon)
- CurrentToken->setType(TT_TableGenDAGArgListColonToAlign);
- else
- CurrentToken->setType(TT_TableGenDAGArgListColon);
- skipToNextNonComment();
- return tryToParseTableGenTokVar();
- }
- return true;
- }
- return false;
- }
-
- // Judge if the token is a operator ID to insert line break in DAGArg.
- // That is, TableGenBreakingDAGArgOperators is empty (by the definition of the
- // option) or the token is in the list.
- bool isTableGenDAGArgBreakingOperator(const FormatToken &Tok) {
- auto &Opes = Style.TableGenBreakingDAGArgOperators;
- // If the list is empty, all operators are breaking operators.
- if (Opes.empty())
- return true;
- // Otherwise, the operator is limited to normal identifiers.
- if (Tok.isNot(tok::identifier) ||
- Tok.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator)) {
- return false;
- }
- // The case next is colon, it is not a operator of identifier.
- if (!Tok.Next || Tok.Next->is(tok::colon))
- return false;
- return llvm::is_contained(Opes, Tok.TokenText.str());
- }
-
- // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
- // This parses SimpleValue 6's inside part of "(" ")"
- bool parseTableGenDAGArgAndList(FormatToken *Opener) {
- FormatToken *FirstTok = CurrentToken;
- if (!parseTableGenDAGArg())
- return false;
- bool BreakInside = false;
- if (Style.TableGenBreakInsideDAGArg != FormatStyle::DAS_DontBreak) {
- // Specialized detection for DAGArgOperator, that determines the way of
- // line break for this DAGArg elements.
- if (isTableGenDAGArgBreakingOperator(*FirstTok)) {
- // Special case for identifier DAGArg operator.
- BreakInside = true;
- Opener->setType(TT_TableGenDAGArgOpenerToBreak);
- if (FirstTok->isOneOf(TT_TableGenBangOperator,
- TT_TableGenCondOperator)) {
- // Special case for bang/cond operators. Set the whole operator as
- // the DAGArg operator. Always break after it.
- CurrentToken->Previous->setType(TT_TableGenDAGArgOperatorToBreak);
- } else if (FirstTok->is(tok::identifier)) {
- if (Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll)
- FirstTok->setType(TT_TableGenDAGArgOperatorToBreak);
- else
- FirstTok->setType(TT_TableGenDAGArgOperatorID);
- }
- }
- }
- // Parse the [DagArgList] part
- return parseTableGenDAGArgList(Opener, BreakInside);
- }
-
- // DagArgList ::= "," DagArg [DagArgList]
- // This parses SimpleValue 6's [DagArgList] part.
- bool parseTableGenDAGArgList(FormatToken *Opener, bool BreakInside) {
- ScopedContextCreator ContextCreator(*this, tok::l_paren, 0);
- Contexts.back().IsTableGenDAGArgList = true;
- bool FirstDAGArgListElm = true;
- while (CurrentToken) {
- if (!FirstDAGArgListElm && CurrentToken->is(tok::comma)) {
- CurrentToken->setType(BreakInside ? TT_TableGenDAGArgListCommaToBreak
- : TT_TableGenDAGArgListComma);
- skipToNextNonComment();
- }
- if (CurrentToken && CurrentToken->is(tok::r_paren)) {
- CurrentToken->setType(TT_TableGenDAGArgCloser);
- Opener->MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = Opener;
- skipToNextNonComment();
- return true;
- }
- if (!parseTableGenDAGArg(
- BreakInside &&
- Style.AlignConsecutiveTableGenBreakingDAGArgColons.Enabled)) {
- return false;
- }
- FirstDAGArgListElm = false;
- }
- return false;
- }
-
- bool parseTableGenSimpleValue() {
- assert(Style.isTableGen());
- if (!CurrentToken)
- return false;
- FormatToken *Tok = CurrentToken;
- skipToNextNonComment();
- // SimpleValue 1, 2, 3: Literals
- if (Tok->isOneOf(tok::numeric_constant, tok::string_literal,
- TT_TableGenMultiLineString, tok::kw_true, tok::kw_false,
- tok::question, tok::kw_int)) {
- return true;
- }
- // SimpleValue 4: ValueList, Type
- if (Tok->is(tok::l_brace)) {
- Scopes.push_back(getScopeType(*Tok));
- return parseBrace();
- }
- // SimpleValue 5: List initializer
- if (Tok->is(tok::l_square)) {
- Tok->setType(TT_TableGenListOpener);
- if (!parseSquare())
- return false;
- if (Tok->is(tok::less)) {
- CurrentToken->setType(TT_TemplateOpener);
- return parseAngle();
- }
- return true;
- }
- // SimpleValue 6: DAGArg [DAGArgList]
- // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
- if (Tok->is(tok::l_paren)) {
- Tok->setType(TT_TableGenDAGArgOpener);
- // Nested DAGArg requires space before '(' as separator.
- if (Contexts.back().IsTableGenDAGArgList)
- Tok->SpacesRequiredBefore = 1;
- return parseTableGenDAGArgAndList(Tok);
- }
- // SimpleValue 9: Bang operator
- if (Tok->is(TT_TableGenBangOperator)) {
- if (CurrentToken && CurrentToken->is(tok::less)) {
- CurrentToken->setType(TT_TemplateOpener);
- skipToNextNonComment();
- if (!parseAngle())
- return false;
- }
- if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
- return false;
- next();
- // FIXME: Hack using inheritance to child context
- Contexts.back().IsTableGenBangOpe = true;
- bool Result = parseParens();
- Contexts.back().IsTableGenBangOpe = false;
- return Result;
- }
- // SimpleValue 9: Cond operator
- if (Tok->is(TT_TableGenCondOperator)) {
- if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
- return false;
- next();
- return parseParens();
- }
- // We have to check identifier at the last because the kind of bang/cond
- // operators are also identifier.
- // SimpleValue 7: Identifiers
- if (Tok->is(tok::identifier)) {
- // SimpleValue 8: Anonymous record
- if (CurrentToken && CurrentToken->is(tok::less)) {
- CurrentToken->setType(TT_TemplateOpener);
- skipToNextNonComment();
- return parseAngle();
- }
- return true;
- }
-
- return false;
- }
-
- bool couldBeInStructArrayInitializer() const {
- if (Contexts.size() < 2)
- return false;
- // We want to back up no more then 2 context levels i.e.
- // . { { <-
- const auto End = std::next(Contexts.rbegin(), 2);
- auto Last = Contexts.rbegin();
- unsigned Depth = 0;
- for (; Last != End; ++Last)
- if (Last->ContextKind == tok::l_brace)
- ++Depth;
- return Depth == 2 && Last->ContextKind != tok::l_brace;
- }
-
- bool parseBrace() {
- if (!CurrentToken)
- return true;
-
- assert(CurrentToken->Previous);
- FormatToken &OpeningBrace = *CurrentToken->Previous;
- assert(OpeningBrace.is(tok::l_brace));
- OpeningBrace.ParentBracket = Contexts.back().ContextKind;
-
- if (Contexts.back().CaretFound)
- OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace);
- Contexts.back().CaretFound = false;
-
- ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
- Contexts.back().ColonIsDictLiteral = true;
- if (OpeningBrace.is(BK_BracedInit))
- Contexts.back().IsExpression = true;
- if (Style.isJavaScript() && OpeningBrace.Previous &&
- OpeningBrace.Previous->is(TT_JsTypeColon)) {
- Contexts.back().IsExpression = false;
- }
- if (Style.isVerilog() &&
- (!OpeningBrace.getPreviousNonComment() ||
- OpeningBrace.getPreviousNonComment()->isNot(Keywords.kw_apostrophe))) {
- Contexts.back().VerilogMayBeConcatenation = true;
- }
- if (Style.isTableGen())
- Contexts.back().ColonIsDictLiteral = false;
-
- unsigned CommaCount = 0;
- while (CurrentToken) {
- if (CurrentToken->is(tok::r_brace)) {
- assert(!Scopes.empty());
- assert(Scopes.back() == getScopeType(OpeningBrace));
- Scopes.pop_back();
- assert(OpeningBrace.Optional == CurrentToken->Optional);
- OpeningBrace.MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = &OpeningBrace;
- if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
- if (OpeningBrace.ParentBracket == tok::l_brace &&
- couldBeInStructArrayInitializer() && CommaCount > 0) {
- Contexts.back().ContextType = Context::StructArrayInitializer;
- }
- }
- next();
- return true;
- }
- if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
- return false;
- updateParameterCount(&OpeningBrace, CurrentToken);
- if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
- FormatToken *Previous = CurrentToken->getPreviousNonComment();
- if (Previous->is(TT_JsTypeOptionalQuestion))
- Previous = Previous->getPreviousNonComment();
- if ((CurrentToken->is(tok::colon) && !Style.isTableGen() &&
- (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
- Style.isProto()) {
- OpeningBrace.setType(TT_DictLiteral);
- if (Previous->Tok.getIdentifierInfo() ||
- Previous->is(tok::string_literal)) {
- Previous->setType(TT_SelectorName);
- }
- }
- if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown) &&
- !Style.isTableGen()) {
- OpeningBrace.setType(TT_DictLiteral);
- } else if (Style.isJavaScript()) {
- OpeningBrace.overwriteFixedType(TT_DictLiteral);
- }
- }
- bool IsBracedListComma = false;
- if (CurrentToken->is(tok::comma)) {
- if (Style.isJavaScript())
- OpeningBrace.overwriteFixedType(TT_DictLiteral);
- else
- IsBracedListComma = OpeningBrace.is(BK_BracedInit);
- ++CommaCount;
- }
- if (!consumeToken())
- return false;
- if (IsBracedListComma)
- Contexts.back().IsExpression = true;
- }
- return true;
- }
-
- void updateParameterCount(FormatToken *Left, FormatToken *Current) {
- // For ObjC methods, the number of parameters is calculated differently as
- // method declarations have a different structure (the parameters are not
- // inside a bracket scope).
- if (Current->is(tok::l_brace) && Current->is(BK_Block))
- ++Left->BlockParameterCount;
- if (Current->is(tok::comma)) {
- ++Left->ParameterCount;
- if (!Left->Role)
- Left->Role.reset(new CommaSeparatedList(Style));
- Left->Role->CommaFound(Current);
- } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
- Left->ParameterCount = 1;
- }
- }
-
- bool parseConditional() {
- while (CurrentToken) {
- if (CurrentToken->is(tok::colon) && CurrentToken->is(TT_Unknown)) {
- CurrentToken->setType(TT_ConditionalExpr);
- next();
- return true;
- }
- if (!consumeToken())
- return false;
- }
- return false;
- }
-
- bool parseTemplateDeclaration() {
- if (!CurrentToken || CurrentToken->isNot(tok::less))
- return false;
-
- CurrentToken->setType(TT_TemplateOpener);
- next();
-
- TemplateDeclarationDepth++;
- const bool WellFormed = parseAngle();
- TemplateDeclarationDepth--;
- if (!WellFormed)
- return false;
-
- if (CurrentToken && TemplateDeclarationDepth == 0)
- CurrentToken->Previous->ClosesTemplateDeclaration = true;
-
- return true;
- }
-
- bool consumeToken() {
- if (IsCpp) {
- const auto *Prev = CurrentToken->getPreviousNonComment();
- if (Prev && Prev->is(TT_AttributeRSquare) &&
- CurrentToken->isOneOf(tok::kw_if, tok::kw_switch, tok::kw_case,
- tok::kw_default, tok::kw_for, tok::kw_while) &&
- mustBreakAfterAttributes(*CurrentToken, Style)) {
- CurrentToken->MustBreakBefore = true;
- }
- }
- FormatToken *Tok = CurrentToken;
- next();
- // In Verilog primitives' state tables, `:`, `?`, and `-` aren't normal
- // operators.
- if (Tok->is(TT_VerilogTableItem))
- return true;
- // Multi-line string itself is a single annotated token.
- if (Tok->is(TT_TableGenMultiLineString))
- return true;
- auto *Prev = Tok->getPreviousNonComment();
- auto *Next = Tok->getNextNonComment();
- switch (bool IsIf = false; Tok->Tok.getKind()) {
- case tok::plus:
- case tok::minus:
- if (!Prev && Line.MustBeDeclaration)
- Tok->setType(TT_ObjCMethodSpecifier);
- break;
- case tok::colon:
- if (!Prev)
- return false;
- // Goto labels and case labels are already identified in
- // UnwrappedLineParser.
- if (Tok->isTypeFinalized())
- break;
- // Colons from ?: are handled in parseConditional().
- if (Style.isJavaScript()) {
- if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
- (Contexts.size() == 1 && // switch/case labels
- Line.First->isNoneOf(tok::kw_enum, tok::kw_case)) ||
- Contexts.back().ContextKind == tok::l_paren || // function params
- Contexts.back().ContextKind == tok::l_square || // array type
- (!Contexts.back().IsExpression &&
- Contexts.back().ContextKind == tok::l_brace) || // object type
- (Contexts.size() == 1 &&
- Line.MustBeDeclaration)) { // method/property declaration
- Contexts.back().IsExpression = false;
- Tok->setType(TT_JsTypeColon);
- break;
- }
- } else if (Style.isCSharp()) {
- if (Contexts.back().InCSharpAttributeSpecifier) {
- Tok->setType(TT_AttributeColon);
- break;
- }
- if (Contexts.back().ContextKind == tok::l_paren) {
- Tok->setType(TT_CSharpNamedArgumentColon);
- break;
- }
- } else if (Style.isVerilog() && Tok->isNot(TT_BinaryOperator)) {
- // The distribution weight operators are labeled
- // TT_BinaryOperator by the lexer.
- if (Keywords.isVerilogEnd(*Prev) || Keywords.isVerilogBegin(*Prev)) {
- Tok->setType(TT_VerilogBlockLabelColon);
- } else if (Contexts.back().ContextKind == tok::l_square) {
- Tok->setType(TT_BitFieldColon);
- } else if (Contexts.back().ColonIsDictLiteral) {
- Tok->setType(TT_DictLiteral);
- } else if (Contexts.size() == 1) {
- // In Verilog a case label doesn't have the case keyword. We
- // assume a colon following an expression is a case label.
- // Colons from ?: are annotated in parseConditional().
- Tok->setType(TT_CaseLabelColon);
- if (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))
- --Line.Level;
- }
- break;
- }
- if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) ||
- Line.First->startsSequence(tok::kw_export, Keywords.kw_module) ||
- Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) {
- Tok->setType(TT_ModulePartitionColon);
- } else if (Line.First->is(tok::kw_asm)) {
- Tok->setType(TT_InlineASMColon);
- } else if (Contexts.back().ColonIsDictLiteral || Style.isProto()) {
- Tok->setType(TT_DictLiteral);
- if (Style.isTextProto())
- Prev->setType(TT_SelectorName);
- } else if (Contexts.back().ColonIsObjCMethodExpr ||
- Line.startsWith(TT_ObjCMethodSpecifier)) {
- Tok->setType(TT_ObjCMethodExpr);
- const auto *PrevPrev = Prev->Previous;
- // Ensure we tag all identifiers in method declarations as
- // TT_SelectorName.
- bool UnknownIdentifierInMethodDeclaration =
- Line.startsWith(TT_ObjCMethodSpecifier) &&
- Prev->is(tok::identifier) && Prev->is(TT_Unknown);
- if (!PrevPrev ||
- // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
- !(PrevPrev->is(TT_CastRParen) ||
- (PrevPrev->is(TT_ObjCMethodExpr) && PrevPrev->is(tok::colon))) ||
- PrevPrev->is(tok::r_square) ||
- Contexts.back().LongestObjCSelectorName == 0 ||
- UnknownIdentifierInMethodDeclaration) {
- Prev->setType(TT_SelectorName);
- if (!Contexts.back().FirstObjCSelectorName)
- Contexts.back().FirstObjCSelectorName = Prev;
- else if (Prev->ColumnWidth > Contexts.back().LongestObjCSelectorName)
- Contexts.back().LongestObjCSelectorName = Prev->ColumnWidth;
- Prev->ParameterIndex =
- Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
- ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
- }
- } else if (Contexts.back().ColonIsForRangeExpr) {
- Tok->setType(TT_RangeBasedForLoopColon);
- for (auto *Token = Prev;
- Token && Token->isNoneOf(tok::semi, tok::l_paren);
- Token = Token->Previous) {
- if (Token->isPointerOrReference())
- Token->setFinalizedType(TT_PointerOrReference);
- }
- } else if (Contexts.back().ContextType == Context::C11GenericSelection) {
- Tok->setType(TT_GenericSelectionColon);
- if (Prev->isPointerOrReference())
- Prev->setFinalizedType(TT_PointerOrReference);
- } else if ((CurrentToken && CurrentToken->is(tok::numeric_constant)) ||
- (Prev->is(TT_StartOfName) && !Scopes.empty() &&
- Scopes.back() == ST_Class)) {
- Tok->setType(TT_BitFieldColon);
- } else if (Contexts.size() == 1 &&
- Line.getFirstNonComment()->isNoneOf(tok::kw_enum, tok::kw_case,
- tok::kw_default) &&
- !Line.startsWith(tok::kw_typedef, tok::kw_enum)) {
- if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept) ||
- Prev->ClosesRequiresClause) {
- Tok->setType(TT_CtorInitializerColon);
- } else if (Prev->is(tok::kw_try)) {
- // Member initializer list within function try block.
- FormatToken *PrevPrev = Prev->getPreviousNonComment();
- if (!PrevPrev)
- break;
- if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept))
- Tok->setType(TT_CtorInitializerColon);
- } else {
- Tok->setType(TT_InheritanceColon);
- if (Prev->isAccessSpecifierKeyword())
- Line.Type = LT_AccessModifier;
- }
- } else if (canBeObjCSelectorComponent(*Prev) && Next &&
- (Next->isOneOf(tok::r_paren, tok::comma) ||
- (canBeObjCSelectorComponent(*Next) && Next->Next &&
- Next->Next->is(tok::colon)))) {
- // This handles a special macro in ObjC code where selectors including
- // the colon are passed as macro arguments.
- Tok->setType(TT_ObjCSelector);
- }
- break;
- case tok::pipe:
- case tok::amp:
- // | and & in declarations/type expressions represent union and
- // intersection types, respectively.
- if (Style.isJavaScript() && !Contexts.back().IsExpression)
- Tok->setType(TT_JsTypeOperator);
- break;
- case tok::kw_if:
- if (Style.isTableGen()) {
- // In TableGen it has the form 'if' <value> 'then'.
- if (!parseTableGenValue())
- return false;
- if (CurrentToken && CurrentToken->is(Keywords.kw_then))
- next(); // skip then
- break;
- }
- if (CurrentToken &&
- CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) {
- next();
- }
- IsIf = true;
- [[fallthrough]];
- case tok::kw_while:
- if (CurrentToken && CurrentToken->is(tok::l_paren)) {
- next();
- if (!parseParens(IsIf))
- return false;
- }
- break;
- case tok::kw_for:
- if (Style.isJavaScript()) {
- // x.for and {for: ...}
- if ((Prev && Prev->is(tok::period)) || (Next && Next->is(tok::colon)))
- break;
- // JS' for await ( ...
- if (CurrentToken && CurrentToken->is(Keywords.kw_await))
- next();
- }
- if (IsCpp && CurrentToken && CurrentToken->is(tok::kw_co_await))
- next();
- Contexts.back().ColonIsForRangeExpr = true;
- if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
- return false;
- next();
- if (!parseParens())
- return false;
- break;
- case tok::l_paren:
- // When faced with 'operator()()', the kw_operator handler incorrectly
- // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
- // the first two parens OverloadedOperators and the second l_paren an
- // OverloadedOperatorLParen.
- if (Prev && Prev->is(tok::r_paren) && Prev->MatchingParen &&
- Prev->MatchingParen->is(TT_OverloadedOperatorLParen)) {
- Prev->setType(TT_OverloadedOperator);
- Prev->MatchingParen->setType(TT_OverloadedOperator);
- Tok->setType(TT_OverloadedOperatorLParen);
- }
-
- if (Style.isVerilog()) {
- // Identify the parameter list and port list in a module instantiation.
- // This is still needed when we already have
- // UnwrappedLineParser::parseVerilogHierarchyHeader because that
- // function is only responsible for the definition, not the
- // instantiation.
- auto IsInstancePort = [&]() {
- const FormatToken *PrevPrev;
- // In the following example all 4 left parentheses will be treated as
- // 'TT_VerilogInstancePortLParen'.
- //
- // module_x instance_1(port_1); // Case A.
- // module_x #(parameter_1) // Case B.
- // instance_2(port_1), // Case C.
- // instance_3(port_1); // Case D.
- if (!Prev || !(PrevPrev = Prev->getPreviousNonComment()))
- return false;
- // Case A.
- if (Keywords.isVerilogIdentifier(*Prev) &&
- Keywords.isVerilogIdentifier(*PrevPrev)) {
- return true;
- }
- // Case B.
- if (Prev->is(Keywords.kw_verilogHash) &&
- Keywords.isVerilogIdentifier(*PrevPrev)) {
- return true;
- }
- // Case C.
- if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::r_paren))
- return true;
- // Case D.
- if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::comma)) {
- const FormatToken *PrevParen = PrevPrev->getPreviousNonComment();
- if (PrevParen && PrevParen->is(tok::r_paren) &&
- PrevParen->MatchingParen &&
- PrevParen->MatchingParen->is(TT_VerilogInstancePortLParen)) {
- return true;
- }
- }
- return false;
- };
-
- if (IsInstancePort())
- Tok->setType(TT_VerilogInstancePortLParen);
- }
-
- if (!parseParens())
- return false;
- if (Line.MustBeDeclaration && Contexts.size() == 1 &&
- !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
- !Line.startsWith(tok::l_paren) &&
- Tok->isNoneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen)) {
- if (!Prev ||
- (!Prev->isAttribute() &&
- Prev->isNoneOf(TT_RequiresClause, TT_LeadingJavaAnnotation,
- TT_BinaryOperator))) {
- Line.MightBeFunctionDecl = true;
- Tok->MightBeFunctionDeclParen = true;
- }
- }
- break;
- case tok::l_square:
- if (Style.isTableGen())
- Tok->setType(TT_TableGenListOpener);
- if (!parseSquare())
- return false;
- break;
- case tok::l_brace:
- if (IsCpp) {
- if (Tok->is(TT_RequiresExpressionLBrace))
- Line.Type = LT_RequiresExpression;
- } else if (Style.isTextProto()) {
- if (Prev && Prev->isNot(TT_DictLiteral))
- Prev->setType(TT_SelectorName);
- }
- Scopes.push_back(getScopeType(*Tok));
- if (!parseBrace())
- return false;
- break;
- case tok::less:
- if (parseAngle()) {
- Tok->setType(TT_TemplateOpener);
- // In TT_Proto, we must distignuish between:
- // map<key, value>
- // msg < item: data >
- // msg: < item: data >
- // In TT_TextProto, map<key, value> does not occur.
- if (Style.isTextProto() ||
- (Style.Language == FormatStyle::LK_Proto && Prev &&
- Prev->isOneOf(TT_SelectorName, TT_DictLiteral))) {
- Tok->setType(TT_DictLiteral);
- if (Prev && Prev->isNot(TT_DictLiteral))
- Prev->setType(TT_SelectorName);
- }
- if (Style.isTableGen())
- Tok->setType(TT_TemplateOpener);
- } else {
- Tok->setType(TT_BinaryOperator);
- NonTemplateLess.insert(Tok);
- CurrentToken = Tok;
- next();
- }
- break;
- case tok::r_paren:
- case tok::r_square:
- return false;
- case tok::r_brace:
- // Don't pop scope when encountering unbalanced r_brace.
- if (!Scopes.empty())
- Scopes.pop_back();
- // Lines can start with '}'.
- if (Prev)
- return false;
- break;
- case tok::greater:
- if (!Style.isTextProto() && Tok->is(TT_Unknown))
- Tok->setType(TT_BinaryOperator);
- if (Prev && Prev->is(TT_TemplateCloser))
- Tok->SpacesRequiredBefore = 1;
- break;
- case tok::kw_operator:
- if (Style.isProto())
- break;
- // Handle C++ user-defined conversion function.
- if (IsCpp && CurrentToken) {
- const auto *Info = CurrentToken->Tok.getIdentifierInfo();
- // What follows Tok is an identifier or a non-operator keyword.
- if (Info && !(CurrentToken->isPlacementOperator() ||
- CurrentToken->is(tok::kw_co_await) ||
- Info->isCPlusPlusOperatorKeyword())) {
- FormatToken *LParen;
- if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
- tok::kw_auto, tok::r_paren)) {
- // Skip `decltype(auto)`.
- LParen = CurrentToken->Next->Next->Next->Next;
- } else {
- // Skip to l_paren.
- for (LParen = CurrentToken->Next;
- LParen && LParen->isNot(tok::l_paren); LParen = LParen->Next) {
- if (LParen->isPointerOrReference())
- LParen->setFinalizedType(TT_PointerOrReference);
- }
- }
- if (LParen && LParen->is(tok::l_paren)) {
- if (!Contexts.back().IsExpression) {
- Tok->setFinalizedType(TT_FunctionDeclarationName);
- LParen->setFinalizedType(TT_FunctionDeclarationLParen);
- }
- break;
- }
- }
- }
- while (CurrentToken &&
- CurrentToken->isNoneOf(tok::l_paren, tok::semi, tok::r_paren)) {
- if (CurrentToken->isOneOf(tok::star, tok::amp))
- CurrentToken->setType(TT_PointerOrReference);
- auto Next = CurrentToken->getNextNonComment();
- if (!Next)
- break;
- if (Next->is(tok::less))
- next();
- else
- consumeToken();
- if (!CurrentToken)
- break;
- auto Previous = CurrentToken->getPreviousNonComment();
- assert(Previous);
- if (CurrentToken->is(tok::comma) && Previous->isNot(tok::kw_operator))
- break;
- if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator, tok::comma,
- tok::arrow) ||
- Previous->isPointerOrReference() ||
- // User defined literal.
- Previous->TokenText.starts_with("\"\"")) {
- Previous->setType(TT_OverloadedOperator);
- if (CurrentToken->isOneOf(tok::less, tok::greater))
- break;
- }
- }
- if (CurrentToken && CurrentToken->is(tok::l_paren))
- CurrentToken->setType(TT_OverloadedOperatorLParen);
- if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
- CurrentToken->Previous->setType(TT_OverloadedOperator);
- break;
- case tok::question:
- if (Style.isJavaScript() && Next &&
- Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
- tok::r_brace, tok::r_square)) {
- // Question marks before semicolons, colons, etc. indicate optional
- // types (fields, parameters), e.g.
- // function(x?: string, y?) {...}
- // class X { y?; }
- Tok->setType(TT_JsTypeOptionalQuestion);
- break;
- }
- // Declarations cannot be conditional expressions, this can only be part
- // of a type declaration.
- if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
- Style.isJavaScript()) {
- break;
- }
- if (Style.isCSharp()) {
- // `Type?)`, `Type?>`, `Type? name;`, and `Type? name =` can only be
- // nullable types.
- if (Next && (Next->isOneOf(tok::r_paren, tok::greater) ||
- Next->startsSequence(tok::identifier, tok::semi) ||
- Next->startsSequence(tok::identifier, tok::equal))) {
- Tok->setType(TT_CSharpNullable);
- break;
- }
-
- // Line.MustBeDeclaration will be true for `Type? name;`.
- // But not
- // cond ? "A" : "B";
- // cond ? id : "B";
- // cond ? cond2 ? "A" : "B" : "C";
- if (!Contexts.back().IsExpression && Line.MustBeDeclaration &&
- (!Next || Next->isNoneOf(tok::identifier, tok::string_literal) ||
- !Next->Next || Next->Next->isNoneOf(tok::colon, tok::question))) {
- Tok->setType(TT_CSharpNullable);
- break;
- }
- }
- parseConditional();
- break;
- case tok::kw_template:
- parseTemplateDeclaration();
- break;
- case tok::comma:
- switch (Contexts.back().ContextType) {
- case Context::CtorInitializer:
- Tok->setType(TT_CtorInitializerComma);
- break;
- case Context::InheritanceList:
- Tok->setType(TT_InheritanceComma);
- break;
- case Context::VerilogInstancePortList:
- Tok->setType(TT_VerilogInstancePortComma);
- break;
- default:
- if (Style.isVerilog() && Contexts.size() == 1 &&
- Line.startsWith(Keywords.kw_assign)) {
- Tok->setFinalizedType(TT_VerilogAssignComma);
- } else if (Contexts.back().FirstStartOfName &&
- (Contexts.size() == 1 || startsWithInitStatement(Line))) {
- Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
- Line.IsMultiVariableDeclStmt = true;
- }
- break;
- }
- if (Contexts.back().ContextType == Context::ForEachMacro)
- Contexts.back().IsExpression = true;
- break;
- case tok::kw_default:
- // Unindent case labels.
- if (Style.isVerilog() && Keywords.isVerilogEndOfLabel(*Tok) &&
- (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))) {
- --Line.Level;
- }
- break;
- case tok::identifier:
- if (Tok->isOneOf(Keywords.kw___has_include,
- Keywords.kw___has_include_next)) {
- parseHasInclude();
- }
- if (IsCpp) {
- if (Next && Next->is(tok::l_paren) && Prev &&
- Prev->isOneOf(tok::kw___cdecl, tok::kw___stdcall,
- tok::kw___fastcall, tok::kw___thiscall,
- tok::kw___regcall, tok::kw___vectorcall)) {
- Tok->setFinalizedType(TT_FunctionDeclarationName);
- Next->setFinalizedType(TT_FunctionDeclarationLParen);
- }
- } else if (Style.isCSharp()) {
- if (Tok->is(Keywords.kw_where) && Next && Next->isNot(tok::l_paren)) {
- Tok->setType(TT_CSharpGenericTypeConstraint);
- parseCSharpGenericTypeConstraint();
- if (!Prev)
- Line.IsContinuation = true;
- }
- } else if (Style.isTableGen()) {
- if (Tok->is(Keywords.kw_assert)) {
- if (!parseTableGenValue())
- return false;
- } else if (Tok->isOneOf(Keywords.kw_def, Keywords.kw_defm) &&
- (!Next || Next->isNoneOf(tok::colon, tok::l_brace))) {
- // The case NameValue appears.
- if (!parseTableGenValue(true))
- return false;
- }
- }
- if (Style.AllowBreakBeforeQtProperty &&
- Contexts.back().ContextType == Context::QtProperty &&
- Tok->isQtProperty()) {
- Tok->setFinalizedType(TT_QtProperty);
- }
- break;
- case tok::arrow:
- if (Tok->isNot(TT_LambdaArrow) && Prev && Prev->is(tok::kw_noexcept))
- Tok->setType(TT_TrailingReturnArrow);
- break;
- case tok::equal:
- // In TableGen, there must be a value after "=";
- if (Style.isTableGen() && !parseTableGenValue())
- return false;
- break;
- default:
- break;
- }
- return true;
- }
-
- void parseCSharpGenericTypeConstraint() {
- int OpenAngleBracketsCount = 0;
- while (CurrentToken) {
- if (CurrentToken->is(tok::less)) {
- // parseAngle is too greedy and will consume the whole line.
- CurrentToken->setType(TT_TemplateOpener);
- ++OpenAngleBracketsCount;
- next();
- } else if (CurrentToken->is(tok::greater)) {
- CurrentToken->setType(TT_TemplateCloser);
- --OpenAngleBracketsCount;
- next();
- } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) {
- // We allow line breaks after GenericTypeConstraintComma's
- // so do not flag commas in Generics as GenericTypeConstraintComma's.
- CurrentToken->setType(TT_CSharpGenericTypeConstraintComma);
- next();
- } else if (CurrentToken->is(Keywords.kw_where)) {
- CurrentToken->setType(TT_CSharpGenericTypeConstraint);
- next();
- } else if (CurrentToken->is(tok::colon)) {
- CurrentToken->setType(TT_CSharpGenericTypeConstraintColon);
- next();
- } else {
- next();
- }
- }
- }
-
- void parseIncludeDirective() {
- if (CurrentToken && CurrentToken->is(tok::less)) {
- next();
- while (CurrentToken) {
- // Mark tokens up to the trailing line comments as implicit string
- // literals.
- if (CurrentToken->isNot(tok::comment) &&
- !CurrentToken->TokenText.starts_with("//")) {
- CurrentToken->setType(TT_ImplicitStringLiteral);
- }
- next();
- }
- }
- }
-
- void parseWarningOrError() {
- next();
- // We still want to format the whitespace left of the first token of the
- // warning or error.
- next();
- while (CurrentToken) {
- CurrentToken->setType(TT_ImplicitStringLiteral);
- next();
- }
- }
-
- void parsePragma() {
- next(); // Consume "pragma".
- if (CurrentToken &&
- CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option,
- Keywords.kw_region)) {
- bool IsMarkOrRegion =
- CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_region);
- next();
- next(); // Consume first token (so we fix leading whitespace).
- while (CurrentToken) {
- if (IsMarkOrRegion || CurrentToken->Previous->is(TT_BinaryOperator))
- CurrentToken->setType(TT_ImplicitStringLiteral);
- next();
- }
- }
- }
-
- void parseHasInclude() {
- if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
- return;
- next(); // '('
- parseIncludeDirective();
- next(); // ')'
- }
-
- LineType parsePreprocessorDirective() {
- bool IsFirstToken = CurrentToken->IsFirst;
- LineType Type = LT_PreprocessorDirective;
- next();
- if (!CurrentToken)
- return Type;
-
- if (Style.isJavaScript() && IsFirstToken) {
- // JavaScript files can contain shebang lines of the form:
- // #!/usr/bin/env node
- // Treat these like C++ #include directives.
- while (CurrentToken) {
- // Tokens cannot be comments here.
- CurrentToken->setType(TT_ImplicitStringLiteral);
- next();
- }
- return LT_ImportStatement;
- }
-
- if (CurrentToken->is(tok::numeric_constant)) {
- CurrentToken->SpacesRequiredBefore = 1;
- return Type;
- }
- // Hashes in the middle of a line can lead to any strange token
- // sequence.
- if (!CurrentToken->Tok.getIdentifierInfo())
- return Type;
- // In Verilog macro expansions start with a backtick just like preprocessor
- // directives. Thus we stop if the word is not a preprocessor directive.
- if (Style.isVerilog() && !Keywords.isVerilogPPDirective(*CurrentToken))
- return LT_Invalid;
- switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
- case tok::pp_include:
- case tok::pp_include_next:
- case tok::pp_import:
- next();
- parseIncludeDirective();
- Type = LT_ImportStatement;
- break;
- case tok::pp_error:
- case tok::pp_warning:
- parseWarningOrError();
- break;
- case tok::pp_pragma:
- parsePragma();
- break;
- case tok::pp_if:
- case tok::pp_elif:
- Contexts.back().IsExpression = true;
- next();
- if (CurrentToken)
- CurrentToken->SpacesRequiredBefore = 1;
- parseLine();
- break;
- default:
- break;
- }
- while (CurrentToken) {
- FormatToken *Tok = CurrentToken;
- next();
- if (Tok->is(tok::l_paren)) {
- parseParens();
- } else if (Tok->isOneOf(Keywords.kw___has_include,
- Keywords.kw___has_include_next)) {
- parseHasInclude();
- }
- }
- return Type;
- }
-
-public:
- LineType parseLine() {
- if (!CurrentToken)
- return LT_Invalid;
- NonTemplateLess.clear();
- if (!Line.InMacroBody && CurrentToken->is(tok::hash)) {
- // We were not yet allowed to use C++17 optional when this was being
- // written. So we used LT_Invalid to mark that the line is not a
- // preprocessor directive.
- auto Type = parsePreprocessorDirective();
- if (Type != LT_Invalid)
- return Type;
- }
-
- // Directly allow to 'import <string-literal>' to support protocol buffer
- // definitions (github.com/google/protobuf) or missing "#" (either way we
- // should not break the line).
- IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
- if ((Style.isJava() && CurrentToken->is(Keywords.kw_package)) ||
- (!Style.isVerilog() && Info &&
- Info->getPPKeywordID() == tok::pp_import && CurrentToken->Next &&
- CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
- tok::kw_static))) {
- next();
- parseIncludeDirective();
- return LT_ImportStatement;
- }
-
- // If this line starts and ends in '<' and '>', respectively, it is likely
- // part of "#define <a/b.h>".
- if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
- parseIncludeDirective();
- return LT_ImportStatement;
- }
-
- // In .proto files, top-level options and package statements are very
- // similar to import statements and should not be line-wrapped.
- if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
- CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
- next();
- if (CurrentToken && CurrentToken->is(tok::identifier)) {
- while (CurrentToken)
- next();
- return LT_ImportStatement;
- }
- }
-
- bool KeywordVirtualFound = false;
- bool ImportStatement = false;
-
- // import {...} from '...';
- if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import))
- ImportStatement = true;
-
- while (CurrentToken) {
- if (CurrentToken->is(tok::kw_virtual))
- KeywordVirtualFound = true;
- if (Style.isJavaScript()) {
- // export {...} from '...';
- // An export followed by "from 'some string';" is a re-export from
- // another module identified by a URI and is treated as a
- // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
- // Just "export {...};" or "export class ..." should not be treated as
- // an import in this sense.
- if (Line.First->is(tok::kw_export) &&
- CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
- CurrentToken->Next->isStringLiteral()) {
- ImportStatement = true;
- }
- if (isClosureImportStatement(*CurrentToken))
- ImportStatement = true;
- }
- if (!consumeToken())
- return LT_Invalid;
- }
- if (const auto Type = Line.Type; Type == LT_AccessModifier ||
- Type == LT_RequiresExpression ||
- Type == LT_SimpleRequirement) {
- return Type;
- }
- if (KeywordVirtualFound)
- return LT_VirtualFunctionDecl;
- if (ImportStatement)
- return LT_ImportStatement;
-
- if (Line.startsWith(TT_ObjCMethodSpecifier)) {
- if (Contexts.back().FirstObjCSelectorName) {
- Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
- Contexts.back().LongestObjCSelectorName;
- }
- return LT_ObjCMethodDecl;
- }
-
- for (const auto &ctx : Contexts)
- if (ctx.ContextType == Context::StructArrayInitializer)
- return LT_ArrayOfStructInitializer;
-
- return LT_Other;
- }
-
-private:
- bool isClosureImportStatement(const FormatToken &Tok) {
- // FIXME: Closure-library specific stuff should not be hard-coded but be
- // configurable.
- return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
- Tok.Next->Next &&
- (Tok.Next->Next->TokenText == "module" ||
- Tok.Next->Next->TokenText == "provide" ||
- Tok.Next->Next->TokenText == "require" ||
- Tok.Next->Next->TokenText == "requireType" ||
- Tok.Next->Next->TokenText == "forwardDeclare") &&
- Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
- }
-
- void resetTokenMetadata() {
- if (!CurrentToken)
- return;
-
- // Reset token type in case we have already looked at it and then
- // recovered from an error (e.g. failure to find the matching >).
- if (!CurrentToken->isTypeFinalized() &&
- CurrentToken->isNoneOf(
- TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
- TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace,
- TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow,
- TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
- TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
- TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
- TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace,
- TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause,
- TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
- TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
- TT_CompoundRequirementLBrace, TT_BracedListLBrace,
- TT_FunctionLikeMacro)) {
- CurrentToken->setType(TT_Unknown);
- }
- CurrentToken->Role.reset();
- CurrentToken->MatchingParen = nullptr;
- CurrentToken->FakeLParens.clear();
- CurrentToken->FakeRParens = 0;
- }
-
- void next() {
- if (!CurrentToken)
- return;
-
- CurrentToken->NestingLevel = Contexts.size() - 1;
- CurrentToken->BindingStrength = Contexts.back().BindingStrength;
- modifyContext(*CurrentToken);
- determineTokenType(*CurrentToken);
- CurrentToken = CurrentToken->Next;
-
- resetTokenMetadata();
- }
-
- /// A struct to hold information valid in a specific context, e.g.
- /// a pair of parenthesis.
- struct Context {
- Context(tok::TokenKind ContextKind, unsigned BindingStrength,
- bool IsExpression)
- : ContextKind(ContextKind), BindingStrength(BindingStrength),
- IsExpression(IsExpression) {}
-
- tok::TokenKind ContextKind;
- unsigned BindingStrength;
- bool IsExpression;
- unsigned LongestObjCSelectorName = 0;
- bool ColonIsForRangeExpr = false;
- bool ColonIsDictLiteral = false;
- bool ColonIsObjCMethodExpr = false;
- FormatToken *FirstObjCSelectorName = nullptr;
- FormatToken *FirstStartOfName = nullptr;
- bool CanBeExpression = true;
- bool CaretFound = false;
- bool InCpp11AttributeSpecifier = false;
- bool InCSharpAttributeSpecifier = false;
- bool InStaticAssertFirstArgument = false;
- bool VerilogAssignmentFound = false;
- // Whether the braces may mean concatenation instead of structure or array
- // literal.
- bool VerilogMayBeConcatenation = false;
- bool IsTableGenDAGArgList = false;
- bool IsTableGenBangOpe = false;
- bool IsTableGenCondOpe = false;
- enum {
- Unknown,
- // Like the part after `:` in a constructor.
- // Context(...) : IsExpression(IsExpression)
- CtorInitializer,
- // Like in the parentheses in a foreach.
- ForEachMacro,
- // Like the inheritance list in a class declaration.
- // class Input : public IO
- InheritanceList,
- // Like in the braced list.
- // int x[] = {};
- StructArrayInitializer,
- // Like in `static_cast<int>`.
- TemplateArgument,
- // C11 _Generic selection.
- C11GenericSelection,
- QtProperty,
- // Like in the outer parentheses in `ffnand ff1(.q());`.
- VerilogInstancePortList,
- } ContextType = Unknown;
- };
-
- /// Puts a new \c Context onto the stack \c Contexts for the lifetime
- /// of each instance.
- struct ScopedContextCreator {
- AnnotatingParser &P;
-
- ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
- unsigned Increase)
- : P(P) {
- P.Contexts.push_back(Context(ContextKind,
- P.Contexts.back().BindingStrength + Increase,
- P.Contexts.back().IsExpression));
- }
-
- ~ScopedContextCreator() {
- if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
- if (P.Contexts.back().ContextType == Context::StructArrayInitializer) {
- P.Contexts.pop_back();
- P.Contexts.back().ContextType = Context::StructArrayInitializer;
- return;
- }
- }
- P.Contexts.pop_back();
- }
- };
-
- void modifyContext(const FormatToken &Current) {
- auto AssignmentStartsExpression = [&]() {
- if (Current.getPrecedence() != prec::Assignment)
- return false;
-
- if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
- return false;
- if (Line.First->is(tok::kw_template)) {
- assert(Current.Previous);
- if (Current.Previous->is(tok::kw_operator)) {
- // `template ... operator=` cannot be an expression.
- return false;
- }
-
- // `template` keyword can start a variable template.
- const FormatToken *Tok = Line.First->getNextNonComment();
- assert(Tok); // Current token is on the same line.
- if (Tok->isNot(TT_TemplateOpener)) {
- // Explicit template instantiations do not have `<>`.
- return false;
- }
-
- // This is the default value of a template parameter, determine if it's
- // type or non-type.
- if (Contexts.back().ContextKind == tok::less) {
- assert(Current.Previous->Previous);
- return Current.Previous->Previous->isNoneOf(tok::kw_typename,
- tok::kw_class);
- }
-
- Tok = Tok->MatchingParen;
- if (!Tok)
- return false;
- Tok = Tok->getNextNonComment();
- if (!Tok)
- return false;
-
- if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_struct,
- tok::kw_using)) {
- return false;
- }
-
- return true;
- }
-
- // Type aliases use `type X = ...;` in TypeScript and can be exported
- // using `export type ...`.
- if (Style.isJavaScript() &&
- (Line.startsWith(Keywords.kw_type, tok::identifier) ||
- Line.startsWith(tok::kw_export, Keywords.kw_type,
- tok::identifier))) {
- return false;
- }
-
- return !Current.Previous || Current.Previous->isNot(tok::kw_operator);
- };
-
- if (AssignmentStartsExpression()) {
- Contexts.back().IsExpression = true;
- if (!Line.startsWith(TT_UnaryOperator)) {
- for (FormatToken *Previous = Current.Previous;
- Previous && Previous->Previous &&
- Previous->Previous->isNoneOf(tok::comma, tok::semi);
- Previous = Previous->Previous) {
- if (Previous->isOneOf(tok::r_square, tok::r_paren, tok::greater)) {
- Previous = Previous->MatchingParen;
- if (!Previous)
- break;
- }
- if (Previous->opensScope())
- break;
- if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
- Previous->isPointerOrReference() && Previous->Previous &&
- Previous->Previous->isNot(tok::equal)) {
- Previous->setType(TT_PointerOrReference);
- }
- }
- }
- } else if (Current.is(tok::lessless) &&
- (!Current.Previous ||
- Current.Previous->isNot(tok::kw_operator))) {
- Contexts.back().IsExpression = true;
- } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
- Contexts.back().IsExpression = true;
- } else if (Current.is(TT_TrailingReturnArrow)) {
- Contexts.back().IsExpression = false;
- } else if (Current.isOneOf(TT_LambdaArrow, Keywords.kw_assert)) {
- Contexts.back().IsExpression = Style.isJava();
- } else if (Current.Previous &&
- Current.Previous->is(TT_CtorInitializerColon)) {
- Contexts.back().IsExpression = true;
- Contexts.back().ContextType = Context::CtorInitializer;
- } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
- Contexts.back().ContextType = Context::InheritanceList;
- } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
- for (FormatToken *Previous = Current.Previous;
- Previous && Previous->isOneOf(tok::star, tok::amp);
- Previous = Previous->Previous) {
- Previous->setType(TT_PointerOrReference);
- }
- if (Line.MustBeDeclaration &&
- Contexts.front().ContextType != Context::CtorInitializer) {
- Contexts.back().IsExpression = false;
- }
- } else if (Current.is(tok::kw_new)) {
- Contexts.back().CanBeExpression = false;
- } else if (Current.is(tok::semi) ||
- (Current.is(tok::exclaim) && Current.Previous &&
- Current.Previous->isNot(tok::kw_operator))) {
- // This should be the condition or increment in a for-loop.
- // But not operator !() (can't use TT_OverloadedOperator here as its not
- // been annotated yet).
- Contexts.back().IsExpression = true;
- }
- }
-
- static FormatToken *untilMatchingParen(FormatToken *Current) {
- // Used when `MatchingParen` is not yet established.
- int ParenLevel = 0;
- while (Current) {
- if (Current->is(tok::l_paren))
- ++ParenLevel;
- if (Current->is(tok::r_paren))
- --ParenLevel;
- if (ParenLevel < 1)
- break;
- Current = Current->Next;
- }
- return Current;
- }
-
- static bool isDeductionGuide(FormatToken &Current) {
- // Look for a deduction guide template<T> A(...) -> A<...>;
- if (Current.Previous && Current.Previous->is(tok::r_paren) &&
- Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
- // Find the TemplateCloser.
- FormatToken *TemplateCloser = Current.Next->Next;
- int NestingLevel = 0;
- while (TemplateCloser) {
- // Skip over an expressions in parens A<(3 < 2)>;
- if (TemplateCloser->is(tok::l_paren)) {
- // No Matching Paren yet so skip to matching paren
- TemplateCloser = untilMatchingParen(TemplateCloser);
- if (!TemplateCloser)
- break;
- }
- if (TemplateCloser->is(tok::less))
- ++NestingLevel;
- if (TemplateCloser->is(tok::greater))
- --NestingLevel;
- if (NestingLevel < 1)
- break;
- TemplateCloser = TemplateCloser->Next;
- }
- // Assuming we have found the end of the template ensure its followed
- // with a semi-colon.
- if (TemplateCloser && TemplateCloser->Next &&
- TemplateCloser->Next->is(tok::semi) &&
- Current.Previous->MatchingParen) {
- // Determine if the identifier `A` prior to the A<..>; is the same as
- // prior to the A(..)
- FormatToken *LeadingIdentifier =
- Current.Previous->MatchingParen->Previous;
-
- return LeadingIdentifier &&
- LeadingIdentifier->TokenText == Current.Next->TokenText;
- }
- }
- return false;
- }
-
- void determineTokenType(FormatToken &Current) {
- if (Current.isNot(TT_Unknown)) {
- // The token type is already known.
- return;
- }
-
- if ((Style.isJavaScript() || Style.isCSharp()) &&
- Current.is(tok::exclaim)) {
- if (Current.Previous) {
- bool IsIdentifier =
- Style.isJavaScript()
- ? Keywords.isJavaScriptIdentifier(
- *Current.Previous, /* AcceptIdentifierName= */ true)
- : Current.Previous->is(tok::identifier);
- if (IsIdentifier ||
- Current.Previous->isOneOf(
- tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square,
- tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type,
- Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) ||
- Current.Previous->Tok.isLiteral()) {
- Current.setType(TT_NonNullAssertion);
- return;
- }
- }
- if (Current.Next &&
- Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
- Current.setType(TT_NonNullAssertion);
- return;
- }
- }
-
- // Line.MightBeFunctionDecl can only be true after the parentheses of a
- // function declaration have been found. In this case, 'Current' is a
- // trailing token of this declaration and thus cannot be a name.
- if ((Style.isJavaScript() || Style.isJava()) &&
- Current.is(Keywords.kw_instanceof)) {
- Current.setType(TT_BinaryOperator);
- } else if (isStartOfName(Current) &&
- (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
- Contexts.back().FirstStartOfName = &Current;
- Current.setType(TT_StartOfName);
- } else if (Current.is(tok::semi)) {
- // Reset FirstStartOfName after finding a semicolon so that a for loop
- // with multiple increment statements is not confused with a for loop
- // having multiple variable declarations.
- Contexts.back().FirstStartOfName = nullptr;
- } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
- AutoFound = true;
- } else if (Current.is(tok::arrow) && Style.isJava()) {
- Current.setType(TT_LambdaArrow);
- } else if (Current.is(tok::arrow) && Style.isVerilog()) {
- // The implication operator.
- Current.setType(TT_BinaryOperator);
- } else if (Current.is(tok::arrow) && AutoFound &&
- Line.MightBeFunctionDecl && Current.NestingLevel == 0 &&
- Current.Previous->isNoneOf(tok::kw_operator, tok::identifier)) {
- // not auto operator->() -> xxx;
- Current.setType(TT_TrailingReturnArrow);
- } else if (Current.is(tok::arrow) && Current.Previous &&
- Current.Previous->is(tok::r_brace) &&
- Current.Previous->is(BK_Block)) {
- // Concept implicit conversion constraint needs to be treated like
- // a trailing return type ... } -> <type>.
- Current.setType(TT_TrailingReturnArrow);
- } else if (isDeductionGuide(Current)) {
- // Deduction guides trailing arrow " A(...) -> A<T>;".
- Current.setType(TT_TrailingReturnArrow);
- } else if (Current.isPointerOrReference()) {
- Current.setType(determineStarAmpUsage(
- Current,
- (Contexts.back().CanBeExpression && Contexts.back().IsExpression) ||
- Contexts.back().InStaticAssertFirstArgument,
- Contexts.back().ContextType == Context::TemplateArgument));
- } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret) ||
- (Style.isVerilog() && Current.is(tok::pipe))) {
- Current.setType(determinePlusMinusCaretUsage(Current));
- if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
- Contexts.back().CaretFound = true;
- } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
- Current.setType(determineIncrementUsage(Current));
- } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
- Current.setType(TT_UnaryOperator);
- } else if (Current.is(tok::question)) {
- if (Style.isJavaScript() && Line.MustBeDeclaration &&
- !Contexts.back().IsExpression) {
- // In JavaScript, `interface X { foo?(): bar; }` is an optional method
- // on the interface, not a ternary expression.
- Current.setType(TT_JsTypeOptionalQuestion);
- } else if (Style.isTableGen()) {
- // In TableGen, '?' is just an identifier like token.
- Current.setType(TT_Unknown);
- } else {
- Current.setType(TT_ConditionalExpr);
- }
- } else if (Current.isBinaryOperator() &&
- (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
- (Current.isNot(tok::greater) && !Style.isTextProto())) {
- if (Style.isVerilog()) {
- if (Current.is(tok::lessequal) && Contexts.size() == 1 &&
- !Contexts.back().VerilogAssignmentFound) {
- // In Verilog `<=` is assignment if in its own statement. It is a
- // statement instead of an expression, that is it can not be chained.
- Current.ForcedPrecedence = prec::Assignment;
- Current.setFinalizedType(TT_BinaryOperator);
- }
- if (Current.getPrecedence() == prec::Assignment)
- Contexts.back().VerilogAssignmentFound = true;
- }
- Current.setType(TT_BinaryOperator);
- } else if (Current.is(tok::comment)) {
- if (Current.TokenText.starts_with("/*")) {
- if (Current.TokenText.ends_with("*/")) {
- Current.setType(TT_BlockComment);
- } else {
- // The lexer has for some reason determined a comment here. But we
- // cannot really handle it, if it isn't properly terminated.
- Current.Tok.setKind(tok::unknown);
- }
- } else {
- Current.setType(TT_LineComment);
- }
- } else if (Current.is(tok::string_literal)) {
- if (Style.isVerilog() && Contexts.back().VerilogMayBeConcatenation &&
- Current.getPreviousNonComment() &&
- Current.getPreviousNonComment()->isOneOf(tok::comma, tok::l_brace) &&
- Current.getNextNonComment() &&
- Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
- Current.setType(TT_StringInConcatenation);
- }
- } else if (Current.is(tok::l_paren)) {
- if (lParenStartsCppCast(Current))
- Current.setType(TT_CppCastLParen);
- } else if (Current.is(tok::r_paren)) {
- if (rParenEndsCast(Current))
- Current.setType(TT_CastRParen);
- if (Current.MatchingParen && Current.Next &&
- !Current.Next->isBinaryOperator() &&
- Current.Next->isNoneOf(
- tok::semi, tok::colon, tok::l_brace, tok::l_paren, tok::comma,
- tok::period, tok::arrow, tok::coloncolon, tok::kw_noexcept)) {
- if (FormatToken *AfterParen = Current.MatchingParen->Next;
- AfterParen && AfterParen->isNot(tok::caret)) {
- // Make sure this isn't the return type of an Obj-C block declaration.
- if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
- BeforeParen && BeforeParen->is(tok::identifier) &&
- BeforeParen->isNot(TT_TypenameMacro) &&
- BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
- (!BeforeParen->Previous ||
- BeforeParen->Previous->ClosesTemplateDeclaration ||
- BeforeParen->Previous->ClosesRequiresClause)) {
- Current.setType(TT_FunctionAnnotationRParen);
- }
- }
- }
- } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() &&
- !Style.isJava()) {
- // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
- // marks declarations and properties that need special formatting.
- switch (Current.Next->Tok.getObjCKeywordID()) {
- case tok::objc_interface:
- case tok::objc_implementation:
- case tok::objc_protocol:
- Current.setType(TT_ObjCDecl);
- break;
- case tok::objc_property:
- Current.setType(TT_ObjCProperty);
- break;
- default:
- break;
- }
- } else if (Current.is(tok::period)) {
- FormatToken *PreviousNoComment = Current.getPreviousNonComment();
- if (PreviousNoComment &&
- PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) {
- Current.setType(TT_DesignatedInitializerPeriod);
- } else if (Style.isJava() && Current.Previous &&
- Current.Previous->isOneOf(TT_JavaAnnotation,
- TT_LeadingJavaAnnotation)) {
- Current.setType(Current.Previous->getType());
- }
- } else if (canBeObjCSelectorComponent(Current) &&
- // FIXME(bug 36976): ObjC return types shouldn't use
- // TT_CastRParen.
- Current.Previous && Current.Previous->is(TT_CastRParen) &&
- Current.Previous->MatchingParen &&
- Current.Previous->MatchingParen->Previous &&
- Current.Previous->MatchingParen->Previous->is(
- TT_ObjCMethodSpecifier)) {
- // This is the first part of an Objective-C selector name. (If there's no
- // colon after this, this is the only place which annotates the identifier
- // as a selector.)
- Current.setType(TT_SelectorName);
- } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept,
- tok::kw_requires) &&
- Current.Previous &&
- Current.Previous->isNoneOf(tok::equal, tok::at,
- TT_CtorInitializerComma,
- TT_CtorInitializerColon) &&
- Line.MightBeFunctionDecl && Contexts.size() == 1) {
- // Line.MightBeFunctionDecl can only be true after the parentheses of a
- // function declaration have been found.
- Current.setType(TT_TrailingAnnotation);
- } else if ((Style.isJava() || Style.isJavaScript()) && Current.Previous) {
- if (Current.Previous->is(tok::at) &&
- Current.isNot(Keywords.kw_interface)) {
- const FormatToken &AtToken = *Current.Previous;
- const FormatToken *Previous = AtToken.getPreviousNonComment();
- if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
- Current.setType(TT_LeadingJavaAnnotation);
- else
- Current.setType(TT_JavaAnnotation);
- } else if (Current.Previous->is(tok::period) &&
- Current.Previous->isOneOf(TT_JavaAnnotation,
- TT_LeadingJavaAnnotation)) {
- Current.setType(Current.Previous->getType());
- }
- }
- }
-
- /// Take a guess at whether \p Tok starts a name of a function or
- /// variable declaration.
- ///
- /// This is a heuristic based on whether \p Tok is an identifier following
- /// something that is likely a type.
- bool isStartOfName(const FormatToken &Tok) {
- // Handled in ExpressionParser for Verilog.
- if (Style.isVerilog())
- return false;
-
- if (!Tok.Previous || Tok.isNot(tok::identifier) || Tok.is(TT_ClassHeadName))
- return false;
-
- if (Tok.endsSequence(Keywords.kw_final, TT_ClassHeadName))
- return false;
-
- if ((Style.isJavaScript() || Style.isJava()) && Tok.is(Keywords.kw_extends))
- return false;
-
- if (const auto *NextNonComment = Tok.getNextNonComment();
- (!NextNonComment && !Line.InMacroBody) ||
- (NextNonComment &&
- (NextNonComment->isPointerOrReference() ||
- NextNonComment->isOneOf(TT_ClassHeadName, tok::string_literal) ||
- (Line.InPragmaDirective && NextNonComment->is(tok::identifier))))) {
- return false;
- }
-
- if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
- Keywords.kw_as)) {
- return false;
- }
- if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in))
- return false;
-
- // Skip "const" as it does not have an influence on whether this is a name.
- FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
-
- // For javascript const can be like "let" or "var"
- if (!Style.isJavaScript())
- while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
- PreviousNotConst = PreviousNotConst->getPreviousNonComment();
-
- if (!PreviousNotConst)
- return false;
-
- if (PreviousNotConst->ClosesRequiresClause)
- return false;
-
- if (Style.isTableGen()) {
- // keywords such as let and def* defines names.
- if (Keywords.isTableGenDefinition(*PreviousNotConst))
- return true;
- // Otherwise C++ style declarations is available only inside the brace.
- if (Contexts.back().ContextKind != tok::l_brace)
- return false;
- }
-
- bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
- PreviousNotConst->Previous &&
- PreviousNotConst->Previous->is(tok::hash);
-
- if (PreviousNotConst->is(TT_TemplateCloser)) {
- return PreviousNotConst && PreviousNotConst->MatchingParen &&
- PreviousNotConst->MatchingParen->Previous &&
- PreviousNotConst->MatchingParen->Previous->isNoneOf(
- tok::period, tok::kw_template);
- }
-
- if ((PreviousNotConst->is(tok::r_paren) &&
- PreviousNotConst->is(TT_TypeDeclarationParen)) ||
- PreviousNotConst->is(TT_AttributeRParen)) {
- return true;
- }
-
- // If is a preprocess keyword like #define.
- if (IsPPKeyword)
- return false;
-
- // int a or auto a.
- if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto) &&
- PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
- return true;
- }
-
- // *a or &a or &&a.
- if (PreviousNotConst->is(TT_PointerOrReference) ||
- PreviousNotConst->endsSequence(tok::coloncolon,
- TT_PointerOrReference)) {
- return true;
- }
-
- // MyClass a;
- if (PreviousNotConst->isTypeName(LangOpts))
- return true;
-
- // type[] a in Java
- if (Style.isJava() && PreviousNotConst->is(tok::r_square))
- return true;
-
- // const a = in JavaScript.
- return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
- }
-
- /// Determine whether '(' is starting a C++ cast.
- bool lParenStartsCppCast(const FormatToken &Tok) {
- // C-style casts are only used in C++.
- if (!IsCpp)
- return false;
-
- FormatToken *LeftOfParens = Tok.getPreviousNonComment();
- if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) &&
- LeftOfParens->MatchingParen) {
- auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment();
- if (Prev &&
- Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast,
- tok::kw_reinterpret_cast, tok::kw_static_cast)) {
- // FIXME: Maybe we should handle identifiers ending with "_cast",
- // e.g. any_cast?
- return true;
- }
- }
- return false;
- }
-
- /// Determine whether ')' is ending a cast.
- bool rParenEndsCast(const FormatToken &Tok) {
- assert(Tok.is(tok::r_paren));
-
- if (!Tok.MatchingParen || !Tok.Previous)
- return false;
-
- // C-style casts are only used in C++, C# and Java.
- if (!IsCpp && !Style.isCSharp() && !Style.isJava())
- return false;
-
- const auto *LParen = Tok.MatchingParen;
- const auto *BeforeRParen = Tok.Previous;
- const auto *AfterRParen = Tok.Next;
-
- // Empty parens aren't casts and there are no casts at the end of the line.
- if (BeforeRParen == LParen || !AfterRParen)
- return false;
-
- if (LParen->isOneOf(TT_OverloadedOperatorLParen, TT_FunctionTypeLParen))
- return false;
-
- auto *LeftOfParens = LParen->getPreviousNonComment();
- if (LeftOfParens) {
- // If there is a closing parenthesis left of the current
- // parentheses, look past it as these might be chained casts.
- if (LeftOfParens->is(tok::r_paren) &&
- LeftOfParens->isNot(TT_CastRParen)) {
- if (!LeftOfParens->MatchingParen ||
- !LeftOfParens->MatchingParen->Previous) {
- return false;
- }
- LeftOfParens = LeftOfParens->MatchingParen->Previous;
- }
-
- if (LeftOfParens->is(tok::r_square)) {
- // delete[] (void *)ptr;
- auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
- if (Tok->isNot(tok::r_square))
- return nullptr;
-
- Tok = Tok->getPreviousNonComment();
- if (!Tok || Tok->isNot(tok::l_square))
- return nullptr;
-
- Tok = Tok->getPreviousNonComment();
- if (!Tok || Tok->isNot(tok::kw_delete))
- return nullptr;
- return Tok;
- };
- if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
- LeftOfParens = MaybeDelete;
- }
-
- // The Condition directly below this one will see the operator arguments
- // as a (void *foo) cast.
- // void operator delete(void *foo) ATTRIB;
- if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
- LeftOfParens->Previous->is(tok::kw_operator)) {
- return false;
- }
-
- // If there is an identifier (or with a few exceptions a keyword) right
- // before the parentheses, this is unlikely to be a cast.
- if (LeftOfParens->Tok.getIdentifierInfo() &&
- LeftOfParens->isNoneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
- tok::kw_delete, tok::kw_throw)) {
- return false;
- }
-
- // Certain other tokens right before the parentheses are also signals that
- // this cannot be a cast.
- if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
- TT_TemplateCloser, tok::ellipsis)) {
- return false;
- }
- }
-
- if (AfterRParen->is(tok::question) ||
- (AfterRParen->is(tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) {
- return false;
- }
-
- // `foreach((A a, B b) in someList)` should not be seen as a cast.
- if (AfterRParen->is(Keywords.kw_in) && Style.isCSharp())
- return false;
-
- // Functions which end with decorations like volatile, noexcept are unlikely
- // to be casts.
- if (AfterRParen->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
- tok::kw_requires, tok::kw_throw, tok::arrow,
- Keywords.kw_override, Keywords.kw_final) ||
- isCppAttribute(IsCpp, *AfterRParen)) {
- return false;
- }
-
- // As Java has no function types, a "(" after the ")" likely means that this
- // is a cast.
- if (Style.isJava() && AfterRParen->is(tok::l_paren))
- return true;
-
- // If a (non-string) literal follows, this is likely a cast.
- if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
- (AfterRParen->Tok.isLiteral() &&
- AfterRParen->isNot(tok::string_literal))) {
- return true;
- }
-
- auto IsNonVariableTemplate = [](const FormatToken &Tok) {
- if (Tok.isNot(TT_TemplateCloser))
- return false;
- const auto *Less = Tok.MatchingParen;
- if (!Less)
- return false;
- const auto *BeforeLess = Less->getPreviousNonComment();
- return BeforeLess && BeforeLess->isNot(TT_VariableTemplate);
- };
-
- // Heuristically try to determine whether the parentheses contain a type.
- auto IsQualifiedPointerOrReference = [](const FormatToken *T,
- const LangOptions &LangOpts) {
- // This is used to handle cases such as x = (foo *const)&y;
- assert(!T->isTypeName(LangOpts) && "Should have already been checked");
- // Strip trailing qualifiers such as const or volatile when checking
- // whether the parens could be a cast to a pointer/reference type.
- while (T) {
- if (T->is(TT_AttributeRParen)) {
- // Handle `x = (foo *__attribute__((foo)))&v;`:
- assert(T->is(tok::r_paren));
- assert(T->MatchingParen);
- assert(T->MatchingParen->is(tok::l_paren));
- assert(T->MatchingParen->is(TT_AttributeLParen));
- if (const auto *Tok = T->MatchingParen->Previous;
- Tok && Tok->isAttribute()) {
- T = Tok->Previous;
- continue;
- }
- } else if (T->is(TT_AttributeRSquare)) {
- // Handle `x = (foo *[[clang::foo]])&v;`:
- if (T->MatchingParen && T->MatchingParen->Previous) {
- T = T->MatchingParen->Previous;
- continue;
- }
- } else if (T->canBePointerOrReferenceQualifier()) {
- T = T->Previous;
- continue;
- }
- break;
- }
- return T && T->is(TT_PointerOrReference);
- };
-
- bool ParensAreType = IsNonVariableTemplate(*BeforeRParen) ||
- BeforeRParen->is(TT_TypeDeclarationParen) ||
- BeforeRParen->isTypeName(LangOpts) ||
- IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
- bool ParensCouldEndDecl =
- AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
- if (ParensAreType && !ParensCouldEndDecl)
- return true;
-
- // At this point, we heuristically assume that there are no casts at the
- // start of the line. We assume that we have found most cases where there
- // are by the logic above, e.g. "(void)x;".
- if (!LeftOfParens)
- return false;
-
- // Certain token types inside the parentheses mean that this can't be a
- // cast.
- for (const auto *Token = LParen->Next; Token != &Tok; Token = Token->Next)
- if (Token->is(TT_BinaryOperator))
- return false;
-
- // If the following token is an identifier or 'this', this is a cast. All
- // cases where this can be something else are handled above.
- if (AfterRParen->isOneOf(tok::identifier, tok::kw_this))
- return true;
-
- // Look for a cast `( x ) (`, where x may be a qualified identifier.
- if (AfterRParen->is(tok::l_paren)) {
- for (const auto *Prev = BeforeRParen; Prev->is(tok::identifier);) {
- Prev = Prev->Previous;
- if (Prev->is(tok::coloncolon))
- Prev = Prev->Previous;
- if (Prev == LParen)
- return true;
- }
- }
-
- if (!AfterRParen->Next)
- return false;
-
- // A pair of parentheses before an l_brace in C starts a compound literal
- // and is not a cast.
- if (Style.Language != FormatStyle::LK_C && AfterRParen->is(tok::l_brace) &&
- AfterRParen->getBlockKind() == BK_BracedInit) {
- return true;
- }
-
- // If the next token after the parenthesis is a unary operator, assume
- // that this is cast, unless there are unexpected tokens inside the
- // parenthesis.
- const bool NextIsAmpOrStar = AfterRParen->isOneOf(tok::amp, tok::star);
- if (!(AfterRParen->isUnaryOperator() || NextIsAmpOrStar) ||
- AfterRParen->is(tok::plus) ||
- AfterRParen->Next->isNoneOf(tok::identifier, tok::numeric_constant)) {
- return false;
- }
-
- if (NextIsAmpOrStar &&
- (AfterRParen->Next->is(tok::numeric_constant) || Line.InPPDirective)) {
- return false;
- }
-
- if (Line.InPPDirective && AfterRParen->is(tok::minus))
- return false;
-
- const auto *Prev = BeforeRParen;
-
- // Look for a function pointer type, e.g. `(*)()`.
- if (Prev->is(tok::r_paren)) {
- if (Prev->is(TT_CastRParen))
- return false;
- Prev = Prev->MatchingParen;
- if (!Prev)
- return false;
- Prev = Prev->Previous;
- if (!Prev || Prev->isNot(tok::r_paren))
- return false;
- Prev = Prev->MatchingParen;
- return Prev && Prev->is(TT_FunctionTypeLParen);
- }
-
- // Search for unexpected tokens.
- for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
- if (Prev->isNoneOf(tok::kw_const, tok::identifier, tok::coloncolon))
- return false;
-
- return true;
- }
-
- /// Returns true if the token is used as a unary operator.
- bool determineUnaryOperatorByUsage(const FormatToken &Tok) {
- const FormatToken *PrevToken = Tok.getPreviousNonComment();
- if (!PrevToken)
- return true;
-
- // These keywords are deliberately not included here because they may
- // precede only one of unary star/amp and plus/minus but not both. They are
- // either included in determineStarAmpUsage or determinePlusMinusCaretUsage.
- //
- // @ - It may be followed by a unary `-` in Objective-C literals. We don't
- // know how they can be followed by a star or amp.
- if (PrevToken->isOneOf(
- TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi,
- tok::equal, tok::question, tok::l_square, tok::l_brace,
- tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield,
- tok::kw_delete, tok::kw_return, tok::kw_throw)) {
- return true;
- }
-
- // We put sizeof here instead of only in determineStarAmpUsage. In the cases
- // where the unary `+` operator is overloaded, it is reasonable to write
- // things like `sizeof +x`. Like commit 446d6ec996c6c3.
- if (PrevToken->is(tok::kw_sizeof))
- return true;
-
- // A sequence of leading unary operators.
- if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
- return true;
-
- // There can't be two consecutive binary operators.
- if (PrevToken->is(TT_BinaryOperator))
- return true;
-
- return false;
- }
-
- /// Return the type of the given token assuming it is * or &.
- TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
- bool InTemplateArgument) {
- if (Style.isJavaScript())
- return TT_BinaryOperator;
-
- // && in C# must be a binary operator.
- if (Style.isCSharp() && Tok.is(tok::ampamp))
- return TT_BinaryOperator;
-
- if (Style.isVerilog()) {
- // In Verilog, `*` can only be a binary operator. `&` can be either unary
- // or binary. `*` also includes `*>` in module path declarations in
- // specify blocks because merged tokens take the type of the first one by
- // default.
- if (Tok.is(tok::star))
- return TT_BinaryOperator;
- return determineUnaryOperatorByUsage(Tok) ? TT_UnaryOperator
- : TT_BinaryOperator;
- }
-
- const FormatToken *PrevToken = Tok.getPreviousNonComment();
- if (!PrevToken)
- return TT_UnaryOperator;
- if (PrevToken->isTypeName(LangOpts))
- return TT_PointerOrReference;
- if (PrevToken->isPlacementOperator() && Tok.is(tok::ampamp))
- return TT_BinaryOperator;
-
- auto *NextToken = Tok.getNextNonComment();
- if (!NextToken)
- return TT_PointerOrReference;
- if (NextToken->is(tok::greater))
- return TT_PointerOrReference;
-
- if (InTemplateArgument && NextToken->is(tok::kw_noexcept))
- return TT_BinaryOperator;
-
- if (NextToken->isOneOf(tok::arrow, tok::equal, tok::comma, tok::r_paren,
- tok::semi, TT_RequiresClause) ||
- (NextToken->is(tok::kw_noexcept) && !IsExpression) ||
- NextToken->canBePointerOrReferenceQualifier() ||
- (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) {
- return TT_PointerOrReference;
- }
-
- if (PrevToken->is(tok::coloncolon))
- return TT_PointerOrReference;
-
- if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
- return TT_PointerOrReference;
-
- if (determineUnaryOperatorByUsage(Tok))
- return TT_UnaryOperator;
-
- if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
- return TT_PointerOrReference;
- if (NextToken->is(tok::kw_operator) && !IsExpression)
- return TT_PointerOrReference;
-
- // After right braces, star tokens are likely to be pointers to struct,
- // union, or class.
- // struct {} *ptr;
- // This by itself is not sufficient to distinguish from multiplication
- // following a brace-initialized expression, as in:
- // int i = int{42} * 2;
- // In the struct case, the part of the struct declaration until the `{` and
- // the `}` are put on separate unwrapped lines; in the brace-initialized
- // case, the matching `{` is on the same unwrapped line, so check for the
- // presence of the matching brace to distinguish between those.
- if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
- !PrevToken->MatchingParen) {
- return TT_PointerOrReference;
- }
-
- if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
- return TT_UnaryOperator;
-
- if (PrevToken->Tok.isLiteral() ||
- PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
- tok::kw_false, tok::r_brace)) {
- return TT_BinaryOperator;
- }
-
- const FormatToken *NextNonParen = NextToken;
- while (NextNonParen && NextNonParen->is(tok::l_paren))
- NextNonParen = NextNonParen->getNextNonComment();
- if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
- NextNonParen->isOneOf(tok::kw_true, tok::kw_false) ||
- NextNonParen->isUnaryOperator())) {
- return TT_BinaryOperator;
- }
-
- // If we know we're in a template argument, there are no named declarations.
- // Thus, having an identifier on the right-hand side indicates a binary
- // operator.
- if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
- return TT_BinaryOperator;
-
- // "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
- // unary "&".
- if (Tok.is(tok::ampamp) &&
- NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
- return TT_BinaryOperator;
- }
-
- // This catches some cases where evaluation order is used as control flow:
- // aaa && aaa->f();
- // Or expressions like:
- // width * height * length
- if (NextToken->Tok.isAnyIdentifier()) {
- auto *NextNextToken = NextToken->getNextNonComment();
- if (NextNextToken) {
- if (NextNextToken->is(tok::arrow))
- return TT_BinaryOperator;
- if (NextNextToken->isPointerOrReference() &&
- !NextToken->isObjCLifetimeQualifier(Style)) {
- NextNextToken->setFinalizedType(TT_BinaryOperator);
- return TT_BinaryOperator;
- }
- }
- }
-
- // It is very unlikely that we are going to find a pointer or reference type
- // definition on the RHS of an assignment.
- if (IsExpression && !Contexts.back().CaretFound &&
- Line.getFirstNonComment()->isNot(
- TT_RequiresClauseInARequiresExpression)) {
- return TT_BinaryOperator;
- }
-
- // Opeartors at class scope are likely pointer or reference members.
- if (!Scopes.empty() && Scopes.back() == ST_Class)
- return TT_PointerOrReference;
-
- // Tokens that indicate member access or chained operator& use.
- auto IsChainedOperatorAmpOrMember = [](const FormatToken *token) {
- return !token || token->isOneOf(tok::amp, tok::period, tok::arrow,
- tok::arrowstar, tok::periodstar);
- };
-
- // It's more likely that & represents operator& than an uninitialized
- // reference.
- if (Tok.is(tok::amp) && PrevToken->Tok.isAnyIdentifier() &&
- IsChainedOperatorAmpOrMember(PrevToken->getPreviousNonComment()) &&
- NextToken && NextToken->Tok.isAnyIdentifier()) {
- if (auto NextNext = NextToken->getNextNonComment();
- NextNext &&
- (IsChainedOperatorAmpOrMember(NextNext) || NextNext->is(tok::semi))) {
- return TT_BinaryOperator;
- }
- }
-
- if (Line.Type == LT_SimpleRequirement ||
- (!Scopes.empty() && Scopes.back() == ST_CompoundRequirement)) {
- return TT_BinaryOperator;
- }
-
- return TT_PointerOrReference;
- }
-
- TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
- if (determineUnaryOperatorByUsage(Tok))
- return TT_UnaryOperator;
-
- const FormatToken *PrevToken = Tok.getPreviousNonComment();
- if (!PrevToken)
- return TT_UnaryOperator;
-
- if (PrevToken->is(tok::at))
- return TT_UnaryOperator;
-
- // Fall back to marking the token as binary operator.
- return TT_BinaryOperator;
- }
-
- /// Determine whether ++/-- are pre- or post-increments/-decrements.
- TokenType determineIncrementUsage(const FormatToken &Tok) {
- const FormatToken *PrevToken = Tok.getPreviousNonComment();
- if (!PrevToken || PrevToken->is(TT_CastRParen))
- return TT_UnaryOperator;
- if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
- return TT_TrailingUnaryOperator;
-
- return TT_UnaryOperator;
- }
-
- SmallVector<Context, 8> Contexts;
-
- const FormatStyle &Style;
- AnnotatedLine &Line;
- FormatToken *CurrentToken;
- bool AutoFound;
- bool IsCpp;
- LangOptions LangOpts;
- const AdditionalKeywords &Keywords;
-
- SmallVector<ScopeType> &Scopes;
-
- // Set of "<" tokens that do not open a template parameter list. If parseAngle
- // determines that a specific token can't be a template opener, it will make
- // same decision irrespective of the decisions for tokens leading up to it.
- // Store this information to prevent this from causing exponential runtime.
- llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
-
- int TemplateDeclarationDepth;
-};
-
-static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
-static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
-
-/// Parses binary expressions by inserting fake parenthesis based on
-/// operator precedence.
-class ExpressionParser {
-public:
- ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
- AnnotatedLine &Line)
- : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
-
- /// Parse expressions with the given operator precedence.
- void parse(int Precedence = 0) {
- // Skip 'return' and ObjC selector colons as they are not part of a binary
- // expression.
- while (Current && (Current->is(tok::kw_return) ||
- (Current->is(tok::colon) &&
- Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) {
- next();
- }
-
- if (!Current || Precedence > PrecedenceArrowAndPeriod)
- return;
-
- // Conditional expressions need to be parsed separately for proper nesting.
- if (Precedence == prec::Conditional) {
- parseConditionalExpr();
- return;
- }
-
- // Parse unary operators, which all have a higher precedence than binary
- // operators.
- if (Precedence == PrecedenceUnaryOperator) {
- parseUnaryOperator();
- return;
- }
-
- FormatToken *Start = Current;
- FormatToken *LatestOperator = nullptr;
- unsigned OperatorIndex = 0;
- // The first name of the current type in a port list.
- FormatToken *VerilogFirstOfType = nullptr;
-
- while (Current) {
- // In Verilog ports in a module header that don't have a type take the
- // type of the previous one. For example,
- // module a(output b,
- // c,
- // output d);
- // In this case there need to be fake parentheses around b and c.
- if (Style.isVerilog() && Precedence == prec::Comma) {
- VerilogFirstOfType =
- verilogGroupDecl(VerilogFirstOfType, LatestOperator);
- }
-
- // Consume operators with higher precedence.
- parse(Precedence + 1);
-
- int CurrentPrecedence = getCurrentPrecedence();
- if (CurrentPrecedence > prec::Conditional &&
- CurrentPrecedence < prec::PointerToMember) {
- // When BreakBinaryOperations is globally OnePerLine (no per-operator
- // rules), flatten all precedence levels so that every operator is
- // treated equally for line-breaking purposes. With per-operator rules
- // we must preserve natural precedence so that higher-precedence
- // sub-expressions (e.g. `x << 8` inside a `|` chain) stay grouped;
- // mustBreakBinaryOperation() handles the forced breaks instead.
- if (Style.BreakBinaryOperations.PerOperator.empty() &&
- Style.BreakBinaryOperations.Default ==
- FormatStyle::BBO_OnePerLine) {
- CurrentPrecedence = prec::Additive;
- }
- }
-
- if (Precedence == CurrentPrecedence && Current &&
- Current->is(TT_SelectorName)) {
- if (LatestOperator)
- addFakeParenthesis(Start, prec::Level(Precedence));
- Start = Current;
- }
-
- if ((Style.isCSharp() || Style.isJavaScript() || Style.isJava()) &&
- Precedence == prec::Additive && Current) {
- // A string can be broken without parentheses around it when it is
- // already in a sequence of strings joined by `+` signs.
- FormatToken *Prev = Current->getPreviousNonComment();
- if (Prev && Prev->is(tok::string_literal) &&
- (Prev == Start || Prev->endsSequence(tok::string_literal, tok::plus,
- TT_StringInConcatenation))) {
- Prev->setType(TT_StringInConcatenation);
- }
- }
-
- // At the end of the line or when an operator with lower precedence is
- // found, insert fake parenthesis and return.
- if (!Current ||
- (Current->closesScope() &&
- (Current->MatchingParen || Current->is(TT_TemplateString))) ||
- (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
- (CurrentPrecedence == prec::Conditional &&
- Precedence == prec::Assignment && Current->is(tok::colon))) {
- break;
- }
-
- // Consume scopes: (), [], <> and {}
- // In addition to that we handle require clauses as scope, so that the
- // constraints in that are correctly indented.
- if (Current->opensScope() ||
- Current->isOneOf(TT_RequiresClause,
- TT_RequiresClauseInARequiresExpression)) {
- // In fragment of a JavaScript template string can look like '}..${' and
- // thus close a scope and open a new one at the same time.
- while (Current && (!Current->closesScope() || Current->opensScope())) {
- next();
- parse();
- }
- next();
- } else {
- // Operator found.
- if (CurrentPrecedence == Precedence) {
- if (LatestOperator)
- LatestOperator->NextOperator = Current;
- LatestOperator = Current;
- Current->OperatorIndex = OperatorIndex;
- ++OperatorIndex;
- }
- next(/*SkipPastLeadingComments=*/Precedence > 0);
- }
- }
-
- // Group variables of the same type.
- if (Style.isVerilog() && Precedence == prec::Comma && VerilogFirstOfType)
- addFakeParenthesis(VerilogFirstOfType, prec::Comma);
-
- if (LatestOperator && (Current || Precedence > 0)) {
- // The requires clauses do not neccessarily end in a semicolon or a brace,
- // but just go over to struct/class or a function declaration, we need to
- // intervene so that the fake right paren is inserted correctly.
- auto End =
- (Start->Previous &&
- Start->Previous->isOneOf(TT_RequiresClause,
- TT_RequiresClauseInARequiresExpression))
- ? [this]() {
- auto Ret = Current ? Current : Line.Last;
- while (!Ret->ClosesRequiresClause && Ret->Previous)
- Ret = Ret->Previous;
- return Ret;
- }()
- : nullptr;
-
- if (Precedence == PrecedenceArrowAndPeriod) {
- // Call expressions don't have a binary operator precedence.
- addFakeParenthesis(Start, prec::Unknown, End);
- } else {
- addFakeParenthesis(Start, prec::Level(Precedence), End);
- }
- }
- }
-
-private:
- /// Gets the precedence (+1) of the given token for binary operators
- /// and other tokens that we treat like binary operators.
- int getCurrentPrecedence() {
- if (Current) {
- const FormatToken *NextNonComment = Current->getNextNonComment();
- if (Current->is(TT_ConditionalExpr))
- return prec::Conditional;
- if (NextNonComment && Current->is(TT_SelectorName) &&
- (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
- (Style.isProto() && NextNonComment->is(tok::less)))) {
- return prec::Assignment;
- }
- if (Current->is(TT_JsComputedPropertyName))
- return prec::Assignment;
- if (Current->is(TT_LambdaArrow))
- return prec::Comma;
- if (Current->is(TT_FatArrow))
- return prec::Assignment;
- if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
- (Current->is(tok::comment) && NextNonComment &&
- NextNonComment->is(TT_SelectorName))) {
- return 0;
- }
- if (Current->is(TT_RangeBasedForLoopColon))
- return prec::Comma;
- if ((Style.isJava() || Style.isJavaScript()) &&
- Current->is(Keywords.kw_instanceof)) {
- return prec::Relational;
- }
- if (Style.isJavaScript() &&
- Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) {
- return prec::Relational;
- }
- if (Current->isOneOf(TT_BinaryOperator, tok::comma))
- return Current->getPrecedence();
- if (Current->isOneOf(tok::period, tok::arrow) &&
- Current->isNot(TT_TrailingReturnArrow)) {
- return PrecedenceArrowAndPeriod;
- }
- if ((Style.isJava() || Style.isJavaScript()) &&
- Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
- Keywords.kw_throws)) {
- return 0;
- }
- // In Verilog case labels are not on separate lines straight out of
- // UnwrappedLineParser. The colon is not part of an expression.
- if (Style.isVerilog() && Current->is(tok::colon))
- return 0;
- }
- return -1;
- }
-
- void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
- FormatToken *End = nullptr) {
- // Do not assign fake parenthesis to tokens that are part of an
- // unexpanded macro call. The line within the macro call contains
- // the parenthesis and commas, and we will not find operators within
- // that structure.
- if (Start->MacroParent)
- return;
-
- Start->FakeLParens.push_back(Precedence);
- if (Precedence > prec::Unknown)
- Start->StartsBinaryExpression = true;
- if (!End && Current)
- End = Current->getPreviousNonComment();
- if (End) {
- ++End->FakeRParens;
- if (Precedence > prec::Unknown)
- End->EndsBinaryExpression = true;
- }
- }
-
- /// Parse unary operator expressions and surround them with fake
- /// parentheses if appropriate.
- void parseUnaryOperator() {
- SmallVector<FormatToken *, 2> Tokens;
- while (Current && Current->is(TT_UnaryOperator)) {
- Tokens.push_back(Current);
- next();
- }
- parse(PrecedenceArrowAndPeriod);
- for (FormatToken *Token : reverse(Tokens)) {
- // The actual precedence doesn't matter.
- addFakeParenthesis(Token, prec::Unknown);
- }
- }
-
- void parseConditionalExpr() {
- while (Current && Current->isTrailingComment())
- next();
- FormatToken *Start = Current;
- parse(prec::LogicalOr);
- if (!Current || Current->isNot(tok::question))
- return;
- next();
- parse(prec::Assignment);
- if (!Current || Current->isNot(TT_ConditionalExpr))
- return;
- next();
- parse(prec::Assignment);
- addFakeParenthesis(Start, prec::Conditional);
- }
-
- void next(bool SkipPastLeadingComments = true) {
- if (Current)
- Current = Current->Next;
- while (Current &&
- (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
- Current->isTrailingComment()) {
- Current = Current->Next;
- }
- }
-
- // Add fake parenthesis around declarations of the same type for example in a
- // module prototype. Return the first port / variable of the current type.
- FormatToken *verilogGroupDecl(FormatToken *FirstOfType,
- FormatToken *PreviousComma) {
- if (!Current)
- return nullptr;
-
- FormatToken *Start = Current;
-
- // Skip attributes.
- while (Start->startsSequence(tok::l_paren, tok::star)) {
- if (!(Start = Start->MatchingParen) ||
- !(Start = Start->getNextNonComment())) {
- return nullptr;
- }
- }
-
- FormatToken *Tok = Start;
-
- if (Tok->is(Keywords.kw_assign))
- Tok = Tok->getNextNonComment();
-
- // Skip any type qualifiers to find the first identifier. It may be either a
- // new type name or a variable name. There can be several type qualifiers
- // preceding a variable name, and we can not tell them apart by looking at
- // the word alone since a macro can be defined as either a type qualifier or
- // a variable name. Thus we use the last word before the dimensions instead
- // of the first word as the candidate for the variable or type name.
- FormatToken *First = nullptr;
- while (Tok) {
- FormatToken *Next = Tok->getNextNonComment();
-
- if (Tok->is(tok::hash)) {
- // Start of a macro expansion.
- First = Tok;
- Tok = Next;
- if (Tok)
- Tok = Tok->getNextNonComment();
- } else if (Tok->is(tok::hashhash)) {
- // Concatenation. Skip.
- Tok = Next;
- if (Tok)
- Tok = Tok->getNextNonComment();
- } else if (Keywords.isVerilogQualifier(*Tok) ||
- Keywords.isVerilogIdentifier(*Tok)) {
- First = Tok;
- Tok = Next;
- // The name may have dots like `interface_foo.modport_foo`.
- while (Tok && Tok->isOneOf(tok::period, tok::coloncolon) &&
- (Tok = Tok->getNextNonComment())) {
- if (Keywords.isVerilogIdentifier(*Tok))
- Tok = Tok->getNextNonComment();
- }
- } else if (!Next) {
- Tok = nullptr;
- } else if (Tok->is(tok::l_paren)) {
- // Make sure the parenthesized list is a drive strength. Otherwise the
- // statement may be a module instantiation in which case we have already
- // found the instance name.
- if (Next->isOneOf(
- Keywords.kw_highz0, Keywords.kw_highz1, Keywords.kw_large,
- Keywords.kw_medium, Keywords.kw_pull0, Keywords.kw_pull1,
- Keywords.kw_small, Keywords.kw_strong0, Keywords.kw_strong1,
- Keywords.kw_supply0, Keywords.kw_supply1, Keywords.kw_weak0,
- Keywords.kw_weak1)) {
- Tok->setType(TT_VerilogStrength);
- Tok = Tok->MatchingParen;
- if (Tok) {
- Tok->setType(TT_VerilogStrength);
- Tok = Tok->getNextNonComment();
- }
- } else {
- break;
- }
- } else if (Tok->is(Keywords.kw_verilogHash)) {
- // Delay control.
- if (Next->is(tok::l_paren))
- Next = Next->MatchingParen;
- if (Next)
- Tok = Next->getNextNonComment();
- } else {
- break;
- }
- }
-
- // Find the second identifier. If it exists it will be the name.
- FormatToken *Second = nullptr;
- // Dimensions.
- while (Tok && Tok->is(tok::l_square) && (Tok = Tok->MatchingParen))
- Tok = Tok->getNextNonComment();
- if (Tok && (Tok->is(tok::hash) || Keywords.isVerilogIdentifier(*Tok)))
- Second = Tok;
-
- // If the second identifier doesn't exist and there are qualifiers, the type
- // is implied.
- FormatToken *TypedName = nullptr;
- if (Second) {
- TypedName = Second;
- if (First && First->is(TT_Unknown))
- First->setType(TT_VerilogDimensionedTypeName);
- } else if (First != Start) {
- // If 'First' is null, then this isn't a declaration, 'TypedName' gets set
- // to null as intended.
- TypedName = First;
- }
-
- if (TypedName) {
- // This is a declaration with a new type.
- if (TypedName->is(TT_Unknown))
- TypedName->setType(TT_StartOfName);
- // Group variables of the previous type.
- if (FirstOfType && PreviousComma) {
- PreviousComma->setType(TT_VerilogTypeComma);
- addFakeParenthesis(FirstOfType, prec::Comma, PreviousComma->Previous);
- }
-
- FirstOfType = TypedName;
-
- // Don't let higher precedence handle the qualifiers. For example if we
- // have:
- // parameter x = 0
- // We skip `parameter` here. This way the fake parentheses for the
- // assignment will be around `x = 0`.
- while (Current && Current != FirstOfType) {
- if (Current->opensScope()) {
- next();
- parse();
- }
- next();
- }
- }
-
- return FirstOfType;
- }
-
- const FormatStyle &Style;
- const AdditionalKeywords &Keywords;
- const AnnotatedLine &Line;
- FormatToken *Current;
-};
-
-} // end anonymous namespace
-
-void TokenAnnotator::setCommentLineLevels(
- SmallVectorImpl<AnnotatedLine *> &Lines) const {
- const AnnotatedLine *NextNonCommentLine = nullptr;
- for (AnnotatedLine *Line : reverse(Lines)) {
- assert(Line->First);
-
- // If the comment is currently aligned with the line immediately following
- // it, that's probably intentional and we should keep it.
- if (NextNonCommentLine && NextNonCommentLine->First->NewlinesBefore < 2 &&
- Line->isComment() && !isClangFormatOff(Line->First->TokenText) &&
- NextNonCommentLine->First->OriginalColumn ==
- Line->First->OriginalColumn) {
- const bool PPDirectiveOrImportStmt =
- NextNonCommentLine->Type == LT_PreprocessorDirective ||
- NextNonCommentLine->Type == LT_ImportStatement;
- if (PPDirectiveOrImportStmt)
- Line->Type = LT_CommentAbovePPDirective;
- // Align comments for preprocessor lines with the # in column 0 if
- // preprocessor lines are not indented. Otherwise, align with the next
- // line.
- Line->Level = Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
- PPDirectiveOrImportStmt
- ? 0
- : NextNonCommentLine->Level;
- } else {
- NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
- }
-
- setCommentLineLevels(Line->Children);
- }
-}
-
-static unsigned maxNestingDepth(const AnnotatedLine &Line) {
- unsigned Result = 0;
- for (const auto *Tok = Line.First; Tok; Tok = Tok->Next)
- Result = std::max(Result, Tok->NestingLevel);
- return Result;
-}
-
-// Returns the token after the first qualifier of the name, or nullptr if there
-// is no qualifier.
-static FormatToken *skipNameQualifier(const FormatToken *Tok) {
- assert(Tok);
-
- // Qualified names must start with an identifier.
- if (Tok->isNot(tok::identifier))
- return nullptr;
-
- Tok = Tok->getNextNonComment();
- if (!Tok)
- return nullptr;
-
- // Consider: A::B::B()
- // Tok --^
- if (Tok->is(tok::coloncolon))
- return Tok->getNextNonComment();
-
- // Consider: A<float>::B<int>::B()
- // Tok --^
- if (Tok->is(TT_TemplateOpener)) {
- Tok = Tok->MatchingParen;
- if (!Tok)
- return nullptr;
-
- Tok = Tok->getNextNonComment();
- if (!Tok)
- return nullptr;
- }
-
- return Tok->is(tok::coloncolon) ? Tok->getNextNonComment() : nullptr;
-}
-
-// Returns the name of a function with no return type, e.g. a constructor or
-// destructor.
-static FormatToken *getFunctionName(const AnnotatedLine &Line,
- FormatToken *&OpeningParen) {
- for (FormatToken *Tok = Line.getFirstNonComment(), *Name = nullptr; Tok;
- Tok = Tok->getNextNonComment()) {
- // Skip C++11 attributes both before and after the function name.
- if (Tok->is(TT_AttributeLSquare)) {
- Tok = Tok->MatchingParen;
- if (!Tok)
- return nullptr;
- continue;
- }
-
- // Make sure the name is followed by a pair of parentheses.
- if (Name) {
- if (Tok->is(tok::l_paren) && Tok->is(TT_Unknown) && Tok->MatchingParen) {
- OpeningParen = Tok;
- return Name;
- }
- return nullptr;
- }
-
- // Skip keywords that may precede the constructor/destructor name.
- if (Tok->isOneOf(tok::kw_friend, tok::kw_inline, tok::kw_virtual,
- tok::kw_constexpr, tok::kw_consteval, tok::kw_explicit)) {
- continue;
- }
-
- // Skip past template typename declarations that may precede the
- // constructor/destructor name.
- if (Tok->is(tok::kw_template)) {
- Tok = Tok->getNextNonComment();
- if (!Tok)
- return nullptr;
-
- // If the next token after the template keyword is not an opening bracket,
- // it is a template instantiation, and not a function.
- if (Tok->isNot(TT_TemplateOpener))
- return nullptr;
-
- Tok = Tok->MatchingParen;
- if (!Tok)
- return nullptr;
-
- continue;
- }
-
- // A qualified name may start from the global namespace.
- if (Tok->is(tok::coloncolon)) {
- Tok = Tok->Next;
- if (!Tok)
- return nullptr;
- }
-
- // Skip to the unqualified part of the name.
- while (auto *Next = skipNameQualifier(Tok))
- Tok = Next;
-
- // Skip the `~` if a destructor name.
- if (Tok->is(tok::tilde)) {
- Tok = Tok->Next;
- if (!Tok)
- return nullptr;
- }
-
- // Make sure the name is not already annotated, e.g. as NamespaceMacro.
- if (Tok->isNot(tok::identifier) || Tok->isNot(TT_Unknown))
- return nullptr;
-
- Name = Tok;
- }
-
- return nullptr;
-}
-
-// Checks if Tok is a constructor/destructor name qualified by its class name.
-static bool isCtorOrDtorName(const FormatToken *Tok) {
- assert(Tok && Tok->is(tok::identifier));
- const auto *Prev = Tok->Previous;
-
- if (Prev && Prev->is(tok::tilde))
- Prev = Prev->Previous;
-
- // Consider: A::A() and A<int>::A()
- if (!Prev || (!Prev->endsSequence(tok::coloncolon, tok::identifier) &&
- !Prev->endsSequence(tok::coloncolon, TT_TemplateCloser))) {
- return false;
- }
-
- assert(Prev->Previous);
- if (Prev->Previous->is(TT_TemplateCloser) && Prev->Previous->MatchingParen) {
- Prev = Prev->Previous->MatchingParen;
- assert(Prev->Previous);
- }
-
- return Prev->Previous->TokenText == Tok->TokenText;
-}
-
-void TokenAnnotator::annotate(AnnotatedLine &Line) {
- if (!Line.InMacroBody)
- MacroBodyScopes.clear();
-
- auto &ScopeStack = Line.InMacroBody ? MacroBodyScopes : Scopes;
- AnnotatingParser Parser(Style, Line, Keywords, ScopeStack);
- Line.Type = Parser.parseLine();
-
- if (!Line.Children.empty()) {
- ScopeStack.push_back(ST_Other);
- const bool InRequiresExpression = Line.Type == LT_RequiresExpression;
- for (auto &Child : Line.Children) {
- if (InRequiresExpression &&
- Child->First->isNoneOf(tok::kw_typename, tok::kw_requires,
- TT_CompoundRequirementLBrace)) {
- Child->Type = LT_SimpleRequirement;
- }
- annotate(*Child);
- }
- // ScopeStack can become empty if Child has an unmatched `}`.
- if (!ScopeStack.empty())
- ScopeStack.pop_back();
- }
-
- // With very deep nesting, ExpressionParser uses lots of stack and the
- // formatting algorithm is very slow. We're not going to do a good job here
- // anyway - it's probably generated code being formatted by mistake.
- // Just skip the whole line.
- if (maxNestingDepth(Line) > 50)
- Line.Type = LT_Invalid;
-
- if (Line.Type == LT_Invalid)
- return;
-
- ExpressionParser ExprParser(Style, Keywords, Line);
- ExprParser.parse();
-
- if (IsCpp) {
- FormatToken *OpeningParen = nullptr;
- auto *Tok = getFunctionName(Line, OpeningParen);
- if (Tok && ((!ScopeStack.empty() && ScopeStack.back() == ST_Class) ||
- Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
- Tok->setFinalizedType(TT_CtorDtorDeclName);
- assert(OpeningParen);
- OpeningParen->setFinalizedType(TT_FunctionDeclarationLParen);
- }
- }
-
- if (Line.startsWith(TT_ObjCMethodSpecifier))
- Line.Type = LT_ObjCMethodDecl;
- else if (Line.startsWith(TT_ObjCDecl))
- Line.Type = LT_ObjCDecl;
- else if (Line.startsWith(TT_ObjCProperty))
- Line.Type = LT_ObjCProperty;
-
- auto *First = Line.First;
- First->SpacesRequiredBefore = 1;
- First->CanBreakBefore = First->MustBreakBefore;
-}
-
-// This function heuristically determines whether 'Current' starts the name of a
-// function declaration.
-static bool isFunctionDeclarationName(const LangOptions &LangOpts,
- const FormatToken &Current,
- const AnnotatedLine &Line,
- FormatToken *&ClosingParen) {
- if (Current.is(TT_FunctionDeclarationName))
- return true;
-
- if (Current.isNoneOf(tok::identifier, tok::kw_operator))
- return false;
-
- const auto *Prev = Current.getPreviousNonComment();
- assert(Prev);
-
- const auto &Previous = *Prev;
-
- if (const auto *PrevPrev = Previous.getPreviousNonComment();
- PrevPrev && PrevPrev->is(TT_ObjCDecl)) {
- return false;
- }
-
- auto skipOperatorName =
- [&LangOpts](const FormatToken *Next) -> const FormatToken * {
- for (; Next; Next = Next->Next) {
- if (Next->is(TT_OverloadedOperatorLParen))
- return Next;
- if (Next->is(TT_OverloadedOperator))
- continue;
- if (Next->isPlacementOperator() || Next->is(tok::kw_co_await)) {
- // For 'new[]' and 'delete[]'.
- if (Next->Next &&
- Next->Next->startsSequence(tok::l_square, tok::r_square)) {
- Next = Next->Next->Next;
- }
- continue;
- }
- if (Next->startsSequence(tok::l_square, tok::r_square)) {
- // For operator[]().
- Next = Next->Next;
- continue;
- }
- if ((Next->isTypeName(LangOpts) || Next->is(tok::identifier)) &&
- Next->Next && Next->Next->isPointerOrReference()) {
- // For operator void*(), operator char*(), operator Foo*().
- Next = Next->Next;
- continue;
- }
- if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
- Next = Next->MatchingParen;
- continue;
- }
-
- break;
- }
- return nullptr;
- };
-
- const auto *Next = Current.Next;
- const bool IsCpp = LangOpts.CXXOperatorNames || LangOpts.C11;
-
- // Find parentheses of parameter list.
- if (Current.is(tok::kw_operator)) {
- if (Line.startsWith(tok::kw_friend))
- return true;
- if (Previous.Tok.getIdentifierInfo() &&
- Previous.isNoneOf(tok::kw_return, tok::kw_co_return)) {
- return true;
- }
- if (Previous.is(tok::r_paren) && Previous.is(TT_TypeDeclarationParen)) {
- assert(Previous.MatchingParen);
- assert(Previous.MatchingParen->is(tok::l_paren));
- assert(Previous.MatchingParen->is(TT_TypeDeclarationParen));
- return true;
- }
- if (!Previous.isPointerOrReference() && Previous.isNot(TT_TemplateCloser))
- return false;
- Next = skipOperatorName(Next);
- } else {
- if (Current.isNot(TT_StartOfName) || Current.NestingLevel != 0)
- return false;
- while (Next && Next->startsSequence(tok::hashhash, tok::identifier))
- Next = Next->Next->Next;
- for (; Next; Next = Next->Next) {
- if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
- Next = Next->MatchingParen;
- } else if (Next->is(tok::coloncolon)) {
- Next = Next->Next;
- if (!Next)
- return false;
- if (Next->is(tok::kw_operator)) {
- Next = skipOperatorName(Next->Next);
- break;
- }
- if (Next->isNot(tok::identifier))
- return false;
- } else if (isCppAttribute(IsCpp, *Next)) {
- Next = Next->MatchingParen;
- if (!Next)
- return false;
- } else if (Next->is(tok::l_paren)) {
- break;
- } else {
- return false;
- }
- }
- }
-
- // Check whether parameter list can belong to a function declaration.
- if (!Next || Next->isNot(tok::l_paren) || !Next->MatchingParen)
- return false;
- ClosingParen = Next->MatchingParen;
- assert(ClosingParen->is(tok::r_paren));
- // If the lines ends with "{", this is likely a function definition.
- if (Line.Last->is(tok::l_brace))
- return true;
- if (Next->Next == ClosingParen)
- return true; // Empty parentheses.
- // If there is an &/&& after the r_paren, this is likely a function.
- if (ClosingParen->Next && ClosingParen->Next->is(TT_PointerOrReference))
- return true;
-
- // Check for K&R C function definitions (and C++ function definitions with
- // unnamed parameters), e.g.:
- // int f(i)
- // {
- // return i + 1;
- // }
- // bool g(size_t = 0, bool b = false)
- // {
- // return !b;
- // }
- if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
- !Line.endsWith(tok::semi)) {
- return true;
- }
-
- for (const FormatToken *Tok = Next->Next; Tok && Tok != ClosingParen;
- Tok = Tok->Next) {
- if (Tok->is(TT_TypeDeclarationParen))
- return true;
- if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
- Tok = Tok->MatchingParen;
- continue;
- }
- if (Tok->is(tok::kw_const) || Tok->isTypeName(LangOpts) ||
- Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
- return true;
- }
- if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
- return false;
- }
- return false;
-}
-
-bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
- assert(Line.MightBeFunctionDecl);
-
- if ((Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
- Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevelDefinitions) &&
- Line.Level > 0) {
- return false;
- }
-
- switch (Style.BreakAfterReturnType) {
- case FormatStyle::RTBS_None:
- case FormatStyle::RTBS_Automatic:
- case FormatStyle::RTBS_ExceptShortType:
- return false;
- case FormatStyle::RTBS_All:
- case FormatStyle::RTBS_TopLevel:
- return true;
- case FormatStyle::RTBS_AllDefinitions:
- case FormatStyle::RTBS_TopLevelDefinitions:
- return Line.mightBeFunctionDefinition();
- }
-
- return false;
-}
-
-void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
- if (Line.Computed)
- return;
-
- Line.Computed = true;
-
- for (AnnotatedLine *ChildLine : Line.Children)
- calculateFormattingInformation(*ChildLine);
-
- auto *First = Line.First;
- First->TotalLength = First->IsMultiline
- ? Style.ColumnLimit
- : Line.FirstStartColumn + First->ColumnWidth;
- bool AlignArrayOfStructures =
- (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
- Line.Type == LT_ArrayOfStructInitializer);
- if (AlignArrayOfStructures)
- calculateArrayInitializerColumnList(Line);
-
- const auto *FirstNonComment = Line.getFirstNonComment();
- bool SeenName = false;
- bool LineIsFunctionDeclaration = false;
- FormatToken *AfterLastAttribute = nullptr;
- FormatToken *ClosingParen = nullptr;
-
- for (auto *Tok = FirstNonComment && FirstNonComment->isNot(tok::kw_using)
- ? FirstNonComment->Next
- : nullptr;
- Tok && Tok->isNot(BK_BracedInit); Tok = Tok->Next) {
- if (Tok->is(TT_StartOfName))
- SeenName = true;
- if (Tok->Previous->EndsCppAttributeGroup)
- AfterLastAttribute = Tok;
- if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
- IsCtorOrDtor ||
- isFunctionDeclarationName(LangOpts, *Tok, Line, ClosingParen)) {
- if (!IsCtorOrDtor)
- Tok->setFinalizedType(TT_FunctionDeclarationName);
- LineIsFunctionDeclaration = true;
- SeenName = true;
- if (ClosingParen) {
- auto *OpeningParen = ClosingParen->MatchingParen;
- assert(OpeningParen);
- if (OpeningParen->is(TT_Unknown))
- OpeningParen->setType(TT_FunctionDeclarationLParen);
- }
- break;
- }
- }
-
- if (IsCpp) {
- if ((LineIsFunctionDeclaration ||
- (FirstNonComment && FirstNonComment->is(TT_CtorDtorDeclName))) &&
- Line.endsWith(tok::semi, tok::r_brace)) {
- auto *Tok = Line.Last->Previous;
- while (Tok->isNot(tok::r_brace))
- Tok = Tok->Previous;
- if (auto *LBrace = Tok->MatchingParen; LBrace && LBrace->is(TT_Unknown)) {
- assert(LBrace->is(tok::l_brace));
- Tok->setBlockKind(BK_Block);
- LBrace->setBlockKind(BK_Block);
- LBrace->setFinalizedType(TT_FunctionLBrace);
- }
- }
-
- if (SeenName && AfterLastAttribute &&
- mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
- AfterLastAttribute->MustBreakBefore = true;
- if (LineIsFunctionDeclaration)
- Line.ReturnTypeWrapped = true;
- }
-
- if (!LineIsFunctionDeclaration) {
- Line.ReturnTypeWrapped = false;
- // Annotate */&/&& in `operator` function calls as binary operators.
- for (const auto *Tok = FirstNonComment; Tok; Tok = Tok->Next) {
- if (Tok->isNot(tok::kw_operator))
- continue;
- do {
- Tok = Tok->Next;
- } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
- if (!Tok || !Tok->MatchingParen)
- break;
- const auto *LeftParen = Tok;
- for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
- Tok = Tok->Next) {
- if (Tok->isNot(tok::identifier))
- continue;
- auto *Next = Tok->Next;
- const bool NextIsBinaryOperator =
- Next && Next->isPointerOrReference() && Next->Next &&
- Next->Next->is(tok::identifier);
- if (!NextIsBinaryOperator)
- continue;
- Next->setType(TT_BinaryOperator);
- Tok = Next;
- }
- }
- } else if (ClosingParen) {
- for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) {
- if (Tok->is(TT_CtorInitializerColon))
- break;
- if (Tok->is(tok::arrow)) {
- Tok->overwriteFixedType(TT_TrailingReturnArrow);
- break;
- }
- if (Tok->isNot(TT_TrailingAnnotation))
- continue;
- const auto *Next = Tok->Next;
- if (!Next || Next->isNot(tok::l_paren))
- continue;
- Tok = Next->MatchingParen;
- if (!Tok)
- break;
- }
- }
- }
-
- if (First->is(TT_ElseLBrace)) {
- First->CanBreakBefore = true;
- First->MustBreakBefore = true;
- }
-
- bool InFunctionDecl = Line.MightBeFunctionDecl;
- bool InParameterList = false;
- for (auto *Current = First->Next; Current; Current = Current->Next) {
- const FormatToken *Prev = Current->Previous;
- if (Current->is(TT_LineComment)) {
- if (Prev->is(BK_BracedInit) && Prev->opensScope()) {
- Current->SpacesRequiredBefore =
- (Style.Cpp11BracedListStyle == FormatStyle::BLS_AlignFirstComment &&
- !Style.SpacesInParensOptions.Other)
- ? 0
- : 1;
- } else if (Prev->is(TT_VerilogMultiLineListLParen)) {
- Current->SpacesRequiredBefore = 0;
- } else {
- Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
- }
-
- // If we find a trailing comment, iterate backwards to determine whether
- // it seems to relate to a specific parameter. If so, break before that
- // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
- // to the previous line in:
- // SomeFunction(a,
- // b, // comment
- // c);
- if (!Current->HasUnescapedNewline) {
- for (FormatToken *Parameter = Current->Previous; Parameter;
- Parameter = Parameter->Previous) {
- if (Parameter->isOneOf(tok::comment, tok::r_brace))
- break;
- if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
- if (Parameter->Previous->isNot(TT_CtorInitializerComma) &&
- Parameter->HasUnescapedNewline) {
- Parameter->MustBreakBefore = true;
- }
- break;
- }
- }
- }
- } else if (!Current->Finalized && Current->SpacesRequiredBefore == 0 &&
- spaceRequiredBefore(Line, *Current)) {
- Current->SpacesRequiredBefore = 1;
- }
-
- const auto &Children = Prev->Children;
- if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
- Current->MustBreakBefore = true;
- } else {
- Current->MustBreakBefore =
- Current->MustBreakBefore || mustBreakBefore(Line, *Current);
- if (!Current->MustBreakBefore && InFunctionDecl &&
- Current->is(TT_FunctionDeclarationName)) {
- Current->MustBreakBefore = mustBreakForReturnType(Line);
- }
- }
-
- Current->CanBreakBefore =
- Current->MustBreakBefore || canBreakBefore(Line, *Current);
-
- if (Current->is(TT_FunctionDeclarationLParen)) {
- InParameterList = true;
- } else if (Current->is(tok::r_paren)) {
- const auto *LParen = Current->MatchingParen;
- if (LParen && LParen->is(TT_FunctionDeclarationLParen))
- InParameterList = false;
- } else if (InParameterList &&
- Current->endsSequence(TT_AttributeMacro,
- TT_PointerOrReference)) {
- Current->CanBreakBefore = false;
- }
-
- unsigned ChildSize = 0;
- if (Prev->Children.size() == 1) {
- FormatToken &LastOfChild = *Prev->Children[0]->Last;
- ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
- : LastOfChild.TotalLength + 1;
- }
- if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
- (Prev->Children.size() == 1 &&
- Prev->Children[0]->First->MustBreakBefore) ||
- Current->IsMultiline) {
- Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
- } else {
- Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
- ChildSize + Current->SpacesRequiredBefore;
- }
-
- if (Current->is(TT_ControlStatementLBrace)) {
- if (Style.ColumnLimit > 0 &&
- Style.BraceWrapping.AfterControlStatement ==
- FormatStyle::BWACS_MultiLine &&
- Line.Level * Style.IndentWidth + Line.Last->TotalLength >
- Style.ColumnLimit) {
- Current->CanBreakBefore = true;
- Current->MustBreakBefore = true;
- }
- } else if (Current->is(TT_CtorInitializerColon)) {
- InFunctionDecl = false;
- }
-
- // FIXME: Only calculate this if CanBreakBefore is true once static
- // initializers etc. are sorted out.
- // FIXME: Move magic numbers to a better place.
-
- // Reduce penalty for aligning ObjC method arguments using the colon
- // alignment as this is the canonical way (still prefer fitting everything
- // into one line if possible). Trying to fit a whole expression into one
- // line should not force other line breaks (e.g. when ObjC method
- // expression is a part of other expression).
- Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
- if (Style.Language == FormatStyle::LK_ObjC &&
- Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
- if (Current->ParameterIndex == 1)
- Current->SplitPenalty += 5 * Current->BindingStrength;
- } else {
- Current->SplitPenalty += 20 * Current->BindingStrength;
- }
- }
-
- calculateUnbreakableTailLengths(Line);
- unsigned IndentLevel = Line.Level;
- for (auto *Current = First; Current; Current = Current->Next) {
- if (Current->Role)
- Current->Role->precomputeFormattingInfos(Current);
- if (Current->MatchingParen &&
- Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
- IndentLevel > 0) {
- --IndentLevel;
- }
- Current->IndentLevel = IndentLevel;
- if (Current->opensBlockOrBlockTypeList(Style))
- ++IndentLevel;
- }
-
- LLVM_DEBUG({ printDebugInfo(Line); });
-}
-
-void TokenAnnotator::calculateUnbreakableTailLengths(
- AnnotatedLine &Line) const {
- unsigned UnbreakableTailLength = 0;
- FormatToken *Current = Line.Last;
- while (Current) {
- Current->UnbreakableTailLength = UnbreakableTailLength;
- if (Current->CanBreakBefore ||
- Current->isOneOf(tok::comment, tok::string_literal)) {
- UnbreakableTailLength = 0;
- } else {
- UnbreakableTailLength +=
- Current->ColumnWidth + Current->SpacesRequiredBefore;
- }
- Current = Current->Previous;
- }
-}
-
-void TokenAnnotator::calculateArrayInitializerColumnList(
- AnnotatedLine &Line) const {
- if (Line.First == Line.Last)
- return;
- auto *CurrentToken = Line.First;
- CurrentToken->ArrayInitializerLineStart = true;
- unsigned Depth = 0;
- while (CurrentToken && CurrentToken != Line.Last) {
- if (CurrentToken->is(tok::l_brace)) {
- CurrentToken->IsArrayInitializer = true;
- if (CurrentToken->Next)
- CurrentToken->Next->MustBreakBefore = true;
- CurrentToken =
- calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
- } else {
- CurrentToken = CurrentToken->Next;
- }
- }
-}
-
-FormatToken *TokenAnnotator::calculateInitializerColumnList(
- AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
- while (CurrentToken && CurrentToken != Line.Last) {
- if (CurrentToken->is(tok::l_brace))
- ++Depth;
- else if (CurrentToken->is(tok::r_brace))
- --Depth;
- if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
- CurrentToken = CurrentToken->Next;
- if (!CurrentToken)
- break;
- CurrentToken->StartsColumn = true;
- CurrentToken = CurrentToken->Previous;
- }
- CurrentToken = CurrentToken->Next;
- }
- return CurrentToken;
-}
-
-unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
- const FormatToken &Tok,
- bool InFunctionDecl) const {
- const FormatToken &Left = *Tok.Previous;
- const FormatToken &Right = Tok;
-
- if (Left.is(tok::semi))
- return 0;
-
- // Language specific handling.
- if (Style.isJava()) {
- if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
- return 1;
- if (Right.is(Keywords.kw_implements))
- return 2;
- if (Left.is(tok::comma) && Left.NestingLevel == 0)
- return 3;
- } else if (Style.isJavaScript()) {
- if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
- return 100;
- if (Left.is(TT_JsTypeColon))
- return 35;
- if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
- (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
- return 100;
- }
- // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
- if (Left.opensScope() && Right.closesScope())
- return 200;
- } else if (Style.Language == FormatStyle::LK_Proto) {
- if (Right.is(tok::l_square))
- return 1;
- if (Right.is(tok::period))
- return 500;
- }
-
- if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
- return 1;
- if (Right.is(tok::l_square)) {
- if (Left.is(tok::r_square))
- return 200;
- // Slightly prefer formatting local lambda definitions like functions.
- if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
- return 35;
- if (Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_ArrayInitializerLSquare,
- TT_DesignatedInitializerLSquare, TT_AttributeLSquare)) {
- return 500;
- }
- }
-
- if (Left.is(tok::coloncolon))
- return Style.PenaltyBreakScopeResolution;
- if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
- tok::kw_operator)) {
- if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
- return 3;
- if (Left.is(TT_StartOfName))
- return 110;
- if (InFunctionDecl && Right.NestingLevel == 0)
- return Style.PenaltyReturnTypeOnItsOwnLine;
- return 200;
- }
- if (Right.is(TT_PointerOrReference))
- return 190;
- if (Right.is(TT_LambdaArrow))
- return 110;
- if (Left.is(tok::equal) && Right.is(tok::l_brace))
- return 160;
- if (Left.is(TT_CastRParen))
- return 100;
- if (Left.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
- return 5000;
- if (Left.is(tok::comment))
- return 1000;
-
- if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
- TT_CtorInitializerColon)) {
- return 2;
- }
-
- if (Right.isMemberAccess()) {
- // Breaking before the "./->" of a chained call/member access is reasonably
- // cheap, as formatting those with one call per line is generally
- // desirable. In particular, it should be cheaper to break before the call
- // than it is to break inside a call's parameters, which could lead to weird
- // "hanging" indents. The exception is the very last "./->" to support this
- // frequent pattern:
- //
- // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
- // dddddddd);
- //
- // which might otherwise be blown up onto many lines. Here, clang-format
- // won't produce "hanging" indents anyway as there is no other trailing
- // call.
- //
- // Also apply higher penalty is not a call as that might lead to a wrapping
- // like:
- //
- // aaaaaaa
- // .aaaaaaaaa.bbbbbbbb(cccccccc);
- const auto *NextOperator = Right.NextOperator;
- const auto Penalty = Style.PenaltyBreakBeforeMemberAccess;
- return NextOperator && NextOperator->Previous->closesScope()
- ? std::min(Penalty, 35u)
- : Penalty;
- }
-
- if (Right.is(TT_TrailingAnnotation) &&
- (!Right.Next || Right.Next->isNot(tok::l_paren))) {
- // Moving trailing annotations to the next line is fine for ObjC method
- // declarations.
- if (Line.startsWith(TT_ObjCMethodSpecifier))
- return 10;
- // Generally, breaking before a trailing annotation is bad unless it is
- // function-like. It seems to be especially preferable to keep standard
- // annotations (i.e. "const", "final" and "override") on the same line.
- // Use a slightly higher penalty after ")" so that annotations like
- // "const override" are kept together.
- bool is_short_annotation = Right.TokenText.size() < 10;
- return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
- }
-
- // In for-loops, prefer breaking at ',' and ';'.
- if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
- return 4;
-
- // In Objective-C method expressions, prefer breaking before "param:" over
- // breaking after it.
- if (Right.is(TT_SelectorName))
- return 0;
- if (Left.is(tok::colon)) {
- if (Left.is(TT_ObjCMethodExpr))
- return Line.MightBeFunctionDecl ? 50 : 500;
- if (Left.is(TT_ObjCSelector))
- return 500;
- }
-
- // In Objective-C type declarations, avoid breaking after the category's
- // open paren (we'll prefer breaking after the protocol list's opening
- // angle bracket, if present).
- if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
- Left.Previous->isOneOf(tok::identifier, tok::greater)) {
- return 500;
- }
-
- if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
- return Style.PenaltyBreakOpenParenthesis;
- if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
- return 100;
- if (Left.is(tok::l_paren) && Left.Previous &&
- (Left.Previous->isOneOf(tok::kw_for, tok::kw__Generic) ||
- Left.Previous->isIf())) {
- return 1000;
- }
- if (Left.is(tok::equal) && InFunctionDecl)
- return 110;
- if (Right.is(tok::r_brace))
- return 1;
- if (Left.is(TT_TemplateOpener))
- return 100;
- if (Left.opensScope()) {
- // If we aren't aligning after opening parens/braces we can always break
- // here unless the style does not want us to place all arguments on the
- // next line.
- if (!Style.AlignAfterOpenBracket &&
- (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) {
- return 0;
- }
- if (Left.is(tok::l_brace) &&
- Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
- return 19;
- }
- return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
- : 19;
- }
- if (Left.is(TT_JavaAnnotation))
- return 50;
-
- if (Left.is(TT_UnaryOperator))
- return 60;
- if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
- Left.Previous->isLabelString() &&
- (Left.NextOperator || Left.OperatorIndex != 0)) {
- return 50;
- }
- if (Right.is(tok::plus) && Left.isLabelString() &&
- (Right.NextOperator || Right.OperatorIndex != 0)) {
- return 25;
- }
- if (Left.is(tok::comma))
- return 1;
- if (Right.is(tok::lessless) && Left.isLabelString() &&
- (Right.NextOperator || Right.OperatorIndex != 1)) {
- return 25;
- }
- if (Right.is(tok::lessless)) {
- // Breaking at a << is really cheap.
- if (Left.isNot(tok::r_paren) || Right.OperatorIndex > 0) {
- // Slightly prefer to break before the first one in log-like statements.
- return 2;
- }
- return 1;
- }
- if (Left.ClosesTemplateDeclaration)
- return Style.PenaltyBreakTemplateDeclaration;
- if (Left.ClosesRequiresClause)
- return 0;
- if (Left.is(TT_ConditionalExpr))
- return prec::Conditional;
- prec::Level Level = Left.getPrecedence();
- if (Level == prec::Unknown)
- Level = Right.getPrecedence();
- if (Level == prec::Assignment)
- return Style.PenaltyBreakAssignment;
- if (Level != prec::Unknown)
- return Level;
-
- return 3;
-}
-
-bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
- if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
- return true;
- if (Right.is(TT_OverloadedOperatorLParen) &&
- Style.SpaceBeforeParensOptions.AfterOverloadedOperator) {
- return true;
- }
- if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
- Right.ParameterCount > 0) {
- return true;
- }
- return false;
-}
-
-bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
- const FormatToken &Left,
- const FormatToken &Right) const {
- if (Left.is(tok::kw_return) &&
- Right.isNoneOf(tok::semi, tok::r_paren, tok::hashhash)) {
- return true;
- }
- if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen &&
- Right.MatchingParen->is(TT_CastRParen)) {
- return true;
- }
- if (Left.is(Keywords.kw_assert) && Style.isJava())
- return true;
- if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
- Left.is(tok::objc_property)) {
- return true;
- }
- if (Right.is(tok::hashhash))
- return Left.is(tok::hash);
- if (Left.isOneOf(tok::hashhash, tok::hash))
- return Right.is(tok::hash);
- if (Style.SpacesInParens == FormatStyle::SIPO_Custom) {
- if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
- return Style.SpacesInParensOptions.InEmptyParentheses;
- if (Style.SpacesInParensOptions.ExceptDoubleParentheses &&
- Left.is(tok::r_paren) && Right.is(tok::r_paren)) {
- auto *InnerLParen = Left.MatchingParen;
- if (InnerLParen && InnerLParen->Previous == Right.MatchingParen) {
- InnerLParen->SpacesRequiredBefore = 0;
- return false;
- }
- }
- const FormatToken *LeftParen = nullptr;
- if (Left.is(tok::l_paren))
- LeftParen = &Left;
- else if (Right.is(tok::r_paren) && Right.MatchingParen)
- LeftParen = Right.MatchingParen;
- if (LeftParen && (LeftParen->is(TT_ConditionLParen) ||
- (LeftParen->Previous &&
- isKeywordWithCondition(*LeftParen->Previous)))) {
- return Style.SpacesInParensOptions.InConditionalStatements;
- }
- }
-
- // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
- if (Left.is(tok::kw_auto) && Right.isOneOf(TT_LambdaLBrace, TT_FunctionLBrace,
- // function return type 'auto'
- TT_FunctionTypeLParen)) {
- return true;
- }
-
- // auto{x} auto(x)
- if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
- return false;
-
- const auto *BeforeLeft = Left.Previous;
-
- // operator co_await(x)
- if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && BeforeLeft &&
- BeforeLeft->is(tok::kw_operator)) {
- return false;
- }
- // co_await (x), co_yield (x), co_return (x)
- if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
- Right.isNoneOf(tok::semi, tok::r_paren)) {
- return true;
- }
-
- if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) {
- return (Right.is(TT_CastRParen) ||
- (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
- ? Style.SpacesInParensOptions.InCStyleCasts
- : Style.SpacesInParensOptions.Other;
- }
- if (Right.isOneOf(tok::semi, tok::comma))
- return false;
- if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
- bool IsLightweightGeneric = Right.MatchingParen &&
- Right.MatchingParen->Next &&
- Right.MatchingParen->Next->is(tok::colon);
- return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
- }
- if (Right.is(tok::less) && Left.is(tok::kw_template))
- return Style.SpaceAfterTemplateKeyword;
- if (Left.isOneOf(tok::exclaim, tok::tilde))
- return false;
- if (Left.is(tok::at) &&
- Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
- tok::numeric_constant, tok::l_paren, tok::l_brace,
- tok::kw_true, tok::kw_false)) {
- return false;
- }
- if (Left.is(tok::colon))
- return Left.isNoneOf(TT_ObjCSelector, TT_ObjCMethodExpr);
- if (Left.is(tok::coloncolon))
- return false;
- if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
- if (Style.isTextProto() ||
- (Style.Language == FormatStyle::LK_Proto &&
- (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
- // Format empty list as `<>`.
- if (Left.is(tok::less) && Right.is(tok::greater))
- return false;
- return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
- }
- // Don't attempt to format operator<(), as it is handled later.
- if (Right.isNot(TT_OverloadedOperatorLParen))
- return false;
- }
- if (Right.is(tok::ellipsis)) {
- return Left.Tok.isLiteral() || (Left.is(tok::identifier) && BeforeLeft &&
- BeforeLeft->is(tok::kw_case));
- }
- if (Left.is(tok::l_square) && Right.is(tok::amp))
- return Style.SpacesInSquareBrackets;
- if (Right.is(TT_PointerOrReference)) {
- if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
- if (!Left.MatchingParen)
- return true;
- FormatToken *TokenBeforeMatchingParen =
- Left.MatchingParen->getPreviousNonComment();
- if (!TokenBeforeMatchingParen || Left.isNot(TT_TypeDeclarationParen))
- return true;
- }
- // Add a space if the previous token is a pointer qualifier or the closing
- // parenthesis of __attribute__(()) expression and the style requires spaces
- // after pointer qualifiers.
- if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
- Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
- (Left.is(TT_AttributeRParen) ||
- Left.canBePointerOrReferenceQualifier())) {
- return true;
- }
- if (Left.Tok.isLiteral())
- return true;
- // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
- if (Left.isTypeOrIdentifier(LangOpts) && Right.Next && Right.Next->Next &&
- Right.Next->Next->is(TT_RangeBasedForLoopColon)) {
- return getTokenPointerOrReferenceAlignment(Right) !=
- FormatStyle::PAS_Left;
- }
- return Left.isNoneOf(TT_PointerOrReference, tok::l_paren) &&
- (getTokenPointerOrReferenceAlignment(Right) !=
- FormatStyle::PAS_Left ||
- (Line.IsMultiVariableDeclStmt &&
- (Left.NestingLevel == 0 ||
- (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
- }
- if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
- (Left.isNot(TT_PointerOrReference) ||
- (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
- !Line.IsMultiVariableDeclStmt))) {
- return true;
- }
- if (Left.is(TT_PointerOrReference)) {
- // Add a space if the next token is a pointer qualifier and the style
- // requires spaces before pointer qualifiers.
- if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
- Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
- Right.canBePointerOrReferenceQualifier()) {
- return true;
- }
- // & 1
- if (Right.Tok.isLiteral())
- return true;
- // & /* comment
- if (Right.is(TT_BlockComment))
- return true;
- // foo() -> const Bar * override/final
- // S::foo() & noexcept/requires
- if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final, tok::kw_noexcept,
- TT_RequiresClause) &&
- Right.isNot(TT_StartOfName)) {
- return true;
- }
- // & {
- if (Right.is(tok::l_brace) && Right.is(BK_Block))
- return true;
- // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
- if (BeforeLeft && BeforeLeft->isTypeOrIdentifier(LangOpts) && Right.Next &&
- Right.Next->is(TT_RangeBasedForLoopColon)) {
- return getTokenPointerOrReferenceAlignment(Left) !=
- FormatStyle::PAS_Right;
- }
- if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
- tok::l_paren)) {
- return false;
- }
- if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
- return false;
- // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone,
- // because it does not take into account nested scopes like lambdas.
- // In multi-variable declaration statements, attach */& to the variable
- // independently of the style. However, avoid doing it if we are in a nested
- // scope, e.g. lambda. We still need to special-case statements with
- // initializers.
- if (Line.IsMultiVariableDeclStmt &&
- (Left.NestingLevel == Line.First->NestingLevel ||
- ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
- startsWithInitStatement(Line)))) {
- return false;
- }
- if (!BeforeLeft)
- return false;
- if (BeforeLeft->is(tok::coloncolon)) {
- if (Left.isNot(tok::star))
- return false;
- assert(Style.PointerAlignment != FormatStyle::PAS_Right);
- if (!Right.startsSequence(tok::identifier, tok::r_paren))
- return true;
- assert(Right.Next);
- const auto *LParen = Right.Next->MatchingParen;
- return !LParen || LParen->isNot(TT_FunctionTypeLParen);
- }
- return BeforeLeft->isNoneOf(tok::l_paren, tok::l_square);
- }
- // Ensure right pointer alignment with ellipsis e.g. int *...P
- if (Left.is(tok::ellipsis) && BeforeLeft &&
- BeforeLeft->isPointerOrReference()) {
- return Style.PointerAlignment != FormatStyle::PAS_Right;
- }
-
- if (Right.is(tok::star) && Left.is(tok::l_paren))
- return false;
- if (Left.is(tok::star) && Right.isPointerOrReference())
- return false;
- if (Right.isPointerOrReference()) {
- const FormatToken *Previous = &Left;
- while (Previous && Previous->isNot(tok::kw_operator)) {
- if (Previous->is(tok::identifier) || Previous->isTypeName(LangOpts)) {
- Previous = Previous->getPreviousNonComment();
- continue;
- }
- if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
- Previous = Previous->MatchingParen->getPreviousNonComment();
- continue;
- }
- if (Previous->is(tok::coloncolon)) {
- Previous = Previous->getPreviousNonComment();
- continue;
- }
- break;
- }
- // Space between the type and the * in:
- // operator void*()
- // operator char*()
- // operator void const*()
- // operator void volatile*()
- // operator /*comment*/ const char*()
- // operator volatile /*comment*/ char*()
- // operator Foo*()
- // operator C<T>*()
- // operator std::Foo*()
- // operator C<T>::D<U>*()
- // dependent on PointerAlignment style.
- if (Previous) {
- if (Previous->endsSequence(tok::kw_operator))
- return Style.PointerAlignment != FormatStyle::PAS_Left;
- if (Previous->isOneOf(tok::kw_const, tok::kw_volatile)) {
- return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
- (Style.SpaceAroundPointerQualifiers ==
- FormatStyle::SAPQ_After) ||
- (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
- }
- }
- }
- if (Style.isCSharp() && Left.is(Keywords.kw_is) && Right.is(tok::l_square))
- return true;
- const auto SpaceRequiredForArrayInitializerLSquare =
- [](const FormatToken &LSquareTok, const FormatStyle &Style) {
- return Style.SpacesInContainerLiterals ||
- (Style.isProto() &&
- Style.Cpp11BracedListStyle == FormatStyle::BLS_Block &&
- LSquareTok.endsSequence(tok::l_square, tok::colon,
- TT_SelectorName));
- };
- if (Left.is(tok::l_square)) {
- return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
- SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
- (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
- TT_LambdaLSquare) &&
- Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
- }
- if (Right.is(tok::r_square)) {
- return Right.MatchingParen &&
- ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
- SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
- Style)) ||
- (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
- TT_StructuredBindingLSquare,
- TT_LambdaLSquare)));
- }
- if (Right.is(tok::l_square) &&
- Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare,
- TT_StructuredBindingLSquare, TT_AttributeLSquare) &&
- Left.isNoneOf(tok::numeric_constant, TT_DictLiteral) &&
- !(Left.isNot(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
- Right.is(TT_ArraySubscriptLSquare))) {
- return false;
- }
- if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
- (Right.is(tok::r_brace) && Right.MatchingParen &&
- Right.MatchingParen->isNot(BK_Block))) {
- return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block ||
- Style.SpacesInParensOptions.Other;
- }
- if (Left.is(TT_BlockComment)) {
- // No whitespace in x(/*foo=*/1), except for JavaScript.
- return Style.isJavaScript() || !Left.TokenText.ends_with("=*/");
- }
-
- // Space between template and attribute.
- // e.g. template <typename T> [[nodiscard]] ...
- if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeLSquare))
- return true;
- // Space before parentheses common for all languages
- if (Right.is(tok::l_paren)) {
- // Function declaration or definition
- if (Line.MightBeFunctionDecl && Right.is(TT_FunctionDeclarationLParen)) {
- if (spaceRequiredBeforeParens(Right))
- return true;
- const auto &Options = Style.SpaceBeforeParensOptions;
- return Line.mightBeFunctionDefinition()
- ? Options.AfterFunctionDefinitionName
- : Options.AfterFunctionDeclarationName;
- }
- if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
- return spaceRequiredBeforeParens(Right);
- if (Left.isOneOf(TT_RequiresClause,
- TT_RequiresClauseInARequiresExpression)) {
- return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
- spaceRequiredBeforeParens(Right);
- }
- if (Left.is(TT_RequiresExpression)) {
- return Style.SpaceBeforeParensOptions.AfterRequiresInExpression ||
- spaceRequiredBeforeParens(Right);
- }
- if (Left.isOneOf(TT_AttributeRParen, TT_AttributeRSquare))
- return true;
- if (Left.is(TT_ForEachMacro)) {
- return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
- spaceRequiredBeforeParens(Right);
- }
- if (Left.is(TT_IfMacro)) {
- return Style.SpaceBeforeParensOptions.AfterIfMacros ||
- spaceRequiredBeforeParens(Right);
- }
- if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
- Left.isPlacementOperator() &&
- Right.isNot(TT_OverloadedOperatorLParen) &&
- !(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
- const auto *RParen = Right.MatchingParen;
- return Style.SpaceBeforeParensOptions.AfterPlacementOperator ||
- (RParen && RParen->is(TT_CastRParen));
- }
- if (Line.Type == LT_ObjCDecl)
- return true;
- if (Left.is(tok::semi))
- return true;
- if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
- tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) ||
- Left.isIf(Line.Type != LT_PreprocessorDirective) ||
- Right.is(TT_ConditionLParen)) {
- return Style.SpaceBeforeParensOptions.AfterControlStatements ||
- spaceRequiredBeforeParens(Right);
- }
-
- // TODO add Operator overloading specific Options to
- // SpaceBeforeParensOptions
- if (Right.is(TT_OverloadedOperatorLParen))
- return spaceRequiredBeforeParens(Right);
-
- // Lambda
- if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
- Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) {
- return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
- spaceRequiredBeforeParens(Right);
- }
- if (!BeforeLeft || BeforeLeft->isNoneOf(tok::period, tok::arrow)) {
- if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
- return Style.SpaceBeforeParensOptions.AfterControlStatements ||
- spaceRequiredBeforeParens(Right);
- }
- if (Left.isPlacementOperator() ||
- (Left.is(tok::r_square) && Left.MatchingParen &&
- Left.MatchingParen->Previous &&
- Left.MatchingParen->Previous->is(tok::kw_delete))) {
- return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
- spaceRequiredBeforeParens(Right);
- }
- }
- auto CompoundLiteral = [](const FormatToken &Tok) {
- if (Tok.isNot(tok::l_paren))
- return false;
- const auto *RParen = Tok.MatchingParen;
- if (!RParen)
- return false;
- const auto *Next = RParen->Next;
- return Next && Next->is(tok::l_brace) && Next->is(BK_BracedInit);
- };
- if (Left.is(tok::kw_sizeof) && CompoundLiteral(Right))
- return true;
- // Handle builtins like identifiers.
- if (Line.Type != LT_PreprocessorDirective &&
- (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) {
- return spaceRequiredBeforeParens(Right);
- }
- return false;
- }
- if (Left.is(tok::at) && Right.isNot(tok::objc_not_keyword))
- return false;
- if (Right.is(TT_UnaryOperator)) {
- return Left.isNoneOf(tok::l_paren, tok::l_square, tok::at) &&
- (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
- }
- // No space between the variable name and the initializer list.
- // A a1{1};
- // Verilog doesn't have such syntax, but it has word operators that are C++
- // identifiers like `a inside {b, c}`. So the rule is not applicable.
- if (!Style.isVerilog() &&
- (Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
- tok::r_paren) ||
- Left.isTypeName(LangOpts)) &&
- Right.is(tok::l_brace) && Right.getNextNonComment() &&
- Right.isNot(BK_Block)) {
- return false;
- }
- if (Left.is(tok::period) || Right.is(tok::period))
- return false;
- // u#str, U#str, L#str, u8#str
- // uR#str, UR#str, LR#str, u8R#str
- if (Right.is(tok::hash) && Left.is(tok::identifier) &&
- (Left.TokenText == "L" || Left.TokenText == "u" ||
- Left.TokenText == "U" || Left.TokenText == "u8" ||
- Left.TokenText == "LR" || Left.TokenText == "uR" ||
- Left.TokenText == "UR" || Left.TokenText == "u8R")) {
- return false;
- }
- if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
- Left.MatchingParen->Previous &&
- Left.MatchingParen->Previous->isOneOf(tok::period, tok::coloncolon)) {
- // Java call to generic function with explicit type:
- // A.<B<C<...>>>DoSomething();
- // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
- return false;
- }
- if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
- return false;
- if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) {
- // Objective-C dictionary literal -> no space after opening brace.
- return false;
- }
- if (Right.is(tok::r_brace) && Right.MatchingParen &&
- Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) {
- // Objective-C dictionary literal -> no space before closing brace.
- return false;
- }
- if (Right.is(TT_TrailingAnnotation) && Right.isOneOf(tok::amp, tok::ampamp) &&
- Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
- (!Right.Next || Right.Next->is(tok::semi))) {
- // Match const and volatile ref-qualifiers without any additional
- // qualifiers such as
- // void Fn() const &;
- return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
- }
-
- return true;
-}
-
-bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
- const FormatToken &Right) const {
- const FormatToken &Left = *Right.Previous;
-
- // If the token is finalized don't touch it (as it could be in a
- // clang-format-off section).
- if (Left.Finalized)
- return Right.hasWhitespaceBefore();
-
- const bool IsVerilog = Style.isVerilog();
- assert(!IsVerilog || !IsCpp);
-
- // Never ever merge two words.
- if (Keywords.isWordLike(Right, IsVerilog) &&
- Keywords.isWordLike(Left, IsVerilog)) {
- return true;
- }
-
- // Leave a space between * and /* to avoid C4138 `comment end` found outside
- // of comment.
- if (Left.is(tok::star) && Right.is(tok::comment))
- return true;
-
- if (Left.is(tok::l_brace) && Right.is(tok::r_brace) &&
- Left.Children.empty()) {
- if (Left.is(BK_Block))
- return Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never;
- if (Style.Cpp11BracedListStyle != FormatStyle::BLS_Block) {
- return Style.SpacesInParens == FormatStyle::SIPO_Custom &&
- Style.SpacesInParensOptions.InEmptyParentheses;
- }
- return Style.SpaceInEmptyBraces == FormatStyle::SIEB_Always;
- }
-
- const auto *BeforeLeft = Left.Previous;
-
- if (IsCpp) {
- if (Left.is(TT_OverloadedOperator) &&
- Right.isOneOf(TT_TemplateOpener, TT_TemplateCloser)) {
- return true;
- }
- // Space between UDL and dot: auto b = 4s .count();
- if (Right.is(tok::period) && Left.is(tok::numeric_constant))
- return true;
- // Space between import <iostream>.
- // or import .....;
- if (Left.is(Keywords.kw_import) &&
- Right.isOneOf(tok::less, tok::ellipsis) &&
- (!BeforeLeft || BeforeLeft->is(tok::kw_export))) {
- return true;
- }
- // Space between `module :` and `import :`.
- if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) &&
- Right.is(TT_ModulePartitionColon)) {
- return true;
- }
-
- if (Right.is(TT_AfterPPDirective))
- return true;
-
- // No space between import foo:bar but keep a space between import :bar;
- if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
- return false;
- // No space between :bar;
- if (Left.is(TT_ModulePartitionColon) &&
- Right.isOneOf(tok::identifier, tok::kw_private)) {
- return false;
- }
- if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
- Line.First->is(Keywords.kw_import)) {
- return false;
- }
- // Space in __attribute__((attr)) ::type.
- if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
- Right.is(tok::coloncolon)) {
- return true;
- }
-
- if (Left.is(tok::kw_operator))
- return Right.is(tok::coloncolon) || Style.SpaceAfterOperatorKeyword;
- if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
- !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) {
- return true;
- }
- if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
- Right.is(TT_TemplateOpener)) {
- return true;
- }
- // C++ Core Guidelines suppression tag, e.g. `[[suppress(type.5)]]`.
- if (Left.is(tok::identifier) && Right.is(tok::numeric_constant))
- return Right.TokenText[0] != '.';
- // `Left` is a keyword (including C++ alternative operator) or identifier.
- if (Left.Tok.getIdentifierInfo() && Right.Tok.isLiteral())
- return true;
- } else if (Style.isProto()) {
- if (Right.is(tok::period) && !(BeforeLeft && BeforeLeft->is(tok::period)) &&
- Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
- Keywords.kw_repeated, Keywords.kw_extend)) {
- return true;
- }
- if (Right.is(tok::l_paren) &&
- Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) {
- return true;
- }
- if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
- return true;
- // Slashes occur in text protocol extension syntax: [type/type] { ... }.
- if (Left.is(tok::slash) || Right.is(tok::slash))
- return false;
- if (Left.MatchingParen &&
- Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
- Right.isOneOf(tok::l_brace, tok::less)) {
- return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
- }
- // A percent is probably part of a formatting specification, such as %lld.
- if (Left.is(tok::percent))
- return false;
- // Preserve the existence of a space before a percent for cases like 0x%04x
- // and "%d %d"
- if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
- return Right.hasWhitespaceBefore();
- } else if (Style.isJson()) {
- if (Right.is(tok::colon) && Left.is(tok::string_literal))
- return Style.SpaceBeforeJsonColon;
- } else if (Style.isCSharp()) {
- // Require spaces around '{' and before '}' unless they appear in
- // interpolated strings. Interpolated strings are merged into a single token
- // so cannot have spaces inserted by this function.
-
- // No space between 'this' and '['
- if (Left.is(tok::kw_this) && Right.is(tok::l_square))
- return false;
-
- // No space between 'new' and '('
- if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
- return false;
-
- // Space before { (including space within '{ {').
- if (Right.is(tok::l_brace))
- return true;
-
- // Spaces inside braces.
- if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
- return true;
-
- if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
- return true;
-
- // Spaces around '=>'.
- if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
- return true;
-
- // No spaces around attribute target colons
- if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
- return false;
-
- // space between type and variable e.g. Dictionary<string,string> foo;
- if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
- return true;
-
- // spaces inside square brackets.
- if (Left.is(tok::l_square) || Right.is(tok::r_square))
- return Style.SpacesInSquareBrackets;
-
- // No space before ? in nullable types.
- if (Right.is(TT_CSharpNullable))
- return false;
-
- // No space before null forgiving '!'.
- if (Right.is(TT_NonNullAssertion))
- return false;
-
- // No space between consecutive commas '[,,]'.
- if (Left.is(tok::comma) && Right.is(tok::comma))
- return false;
-
- // space after var in `var (key, value)`
- if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
- return true;
-
- // space between keywords and paren e.g. "using ("
- if (Right.is(tok::l_paren)) {
- if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
- Keywords.kw_lock)) {
- return Style.SpaceBeforeParensOptions.AfterControlStatements ||
- spaceRequiredBeforeParens(Right);
- }
- }
-
- // space between method modifier and opening parenthesis of a tuple return
- // type
- if ((Left.isAccessSpecifierKeyword() ||
- Left.isOneOf(tok::kw_virtual, tok::kw_extern, tok::kw_static,
- Keywords.kw_internal, Keywords.kw_abstract,
- Keywords.kw_sealed, Keywords.kw_override,
- Keywords.kw_async, Keywords.kw_unsafe)) &&
- Right.is(tok::l_paren)) {
- return true;
- }
- } else if (Style.isJavaScript()) {
- if (Left.is(TT_FatArrow))
- return true;
- // for await ( ...
- if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && BeforeLeft &&
- BeforeLeft->is(tok::kw_for)) {
- return true;
- }
- if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
- Right.MatchingParen) {
- const FormatToken *Next = Right.MatchingParen->getNextNonComment();
- // An async arrow function, for example: `x = async () => foo();`,
- // as opposed to calling a function called async: `x = async();`
- if (Next && Next->is(TT_FatArrow))
- return true;
- }
- if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
- (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
- return false;
- }
- // In tagged template literals ("html`bar baz`"), there is no space between
- // the tag identifier and the template string.
- if (Keywords.isJavaScriptIdentifier(Left,
- /* AcceptIdentifierName= */ false) &&
- Right.is(TT_TemplateString)) {
- return false;
- }
- if (Right.is(tok::star) &&
- Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) {
- return false;
- }
- if (Right.isOneOf(tok::l_brace, tok::l_square) &&
- Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
- Keywords.kw_extends, Keywords.kw_implements)) {
- return true;
- }
- if (Right.is(tok::l_paren)) {
- // JS methods can use some keywords as names (e.g. `delete()`).
- if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
- return false;
- // Valid JS method names can include keywords, e.g. `foo.delete()` or
- // `bar.instanceof()`. Recognize call positions by preceding period.
- if (BeforeLeft && BeforeLeft->is(tok::period) &&
- Left.Tok.getIdentifierInfo()) {
- return false;
- }
- // Additional unary JavaScript operators that need a space after.
- if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
- tok::kw_void)) {
- return true;
- }
- }
- // `foo as const;` casts into a const type.
- if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
- return false;
- if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
- tok::kw_const) ||
- // "of" is only a keyword if it appears after another identifier
- // (e.g. as "const x of y" in a for loop), or after a destructuring
- // operation (const [x, y] of z, const {a, b} of c).
- (Left.is(Keywords.kw_of) && BeforeLeft &&
- BeforeLeft->isOneOf(tok::identifier, tok::r_square, tok::r_brace))) &&
- (!BeforeLeft || BeforeLeft->isNot(tok::period))) {
- return true;
- }
- if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && BeforeLeft &&
- BeforeLeft->is(tok::period) && Right.is(tok::l_paren)) {
- return false;
- }
- if (Left.is(Keywords.kw_as) &&
- Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) {
- return true;
- }
- if (Left.is(tok::kw_default) && BeforeLeft &&
- BeforeLeft->is(tok::kw_export)) {
- return true;
- }
- if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
- return true;
- if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
- return false;
- if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
- return false;
- if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
- Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) {
- return false;
- }
- if (Left.is(tok::ellipsis))
- return false;
- if (Left.is(TT_TemplateCloser) &&
- Right.isNoneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
- Keywords.kw_implements, Keywords.kw_extends)) {
- // Type assertions ('<type>expr') are not followed by whitespace. Other
- // locations that should have whitespace following are identified by the
- // above set of follower tokens.
- return false;
- }
- if (Right.is(TT_NonNullAssertion))
- return false;
- if (Left.is(TT_NonNullAssertion) &&
- Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) {
- return true; // "x! as string", "x! in y"
- }
- } else if (Style.isJava()) {
- if (Left.is(TT_CaseLabelArrow) || Right.is(TT_CaseLabelArrow))
- return true;
- if (Left.is(tok::r_square) && Right.is(tok::l_brace))
- return true;
- // spaces inside square brackets.
- if (Left.is(tok::l_square) || Right.is(tok::r_square))
- return Style.SpacesInSquareBrackets;
-
- if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) {
- return Style.SpaceBeforeParensOptions.AfterControlStatements ||
- spaceRequiredBeforeParens(Right);
- }
- if ((Left.isAccessSpecifierKeyword() ||
- Left.isOneOf(tok::kw_static, Keywords.kw_final, Keywords.kw_abstract,
- Keywords.kw_native)) &&
- Right.is(TT_TemplateOpener)) {
- return true;
- }
- } else if (IsVerilog) {
- // An escaped identifier ends with whitespace.
- if (Left.is(tok::identifier) && Left.TokenText[0] == '\\')
- return true;
- // Add space between things in a primitive's state table unless in a
- // transition like `(0?)`.
- if ((Left.is(TT_VerilogTableItem) &&
- Right.isNoneOf(tok::r_paren, tok::semi)) ||
- (Right.is(TT_VerilogTableItem) && Left.isNot(tok::l_paren))) {
- const FormatToken *Next = Right.getNextNonComment();
- return !(Next && Next->is(tok::r_paren));
- }
- // Don't add space within a delay like `#0`.
- if (Left.isNot(TT_BinaryOperator) &&
- Left.isOneOf(Keywords.kw_verilogHash, Keywords.kw_verilogHashHash)) {
- return false;
- }
- // Add space after a delay.
- if (Right.isNot(tok::semi) &&
- (Left.endsSequence(tok::numeric_constant, Keywords.kw_verilogHash) ||
- Left.endsSequence(tok::numeric_constant,
- Keywords.kw_verilogHashHash) ||
- (Left.is(tok::r_paren) && Left.MatchingParen &&
- Left.MatchingParen->endsSequence(tok::l_paren, tok::at)))) {
- return true;
- }
- // Don't add embedded spaces in a number literal like `16'h1?ax` or an array
- // literal like `'{}`.
- if (Left.is(Keywords.kw_apostrophe) ||
- (Left.is(TT_VerilogNumberBase) && Right.is(tok::numeric_constant))) {
- return false;
- }
- // Add spaces around the implication operator `->`.
- if (Left.is(tok::arrow) || Right.is(tok::arrow))
- return true;
- // Don't add spaces between two at signs. Like in a coverage event.
- // Don't add spaces between at and a sensitivity list like
- // `@(posedge clk)`.
- if (Left.is(tok::at) && Right.isOneOf(tok::l_paren, tok::star, tok::at))
- return false;
- // Add space between the type name and dimension like `logic [1:0]`.
- if (Right.is(tok::l_square) &&
- Left.isOneOf(TT_VerilogDimensionedTypeName, Keywords.kw_function)) {
- return true;
- }
- // In a tagged union expression, there should be a space after the tag.
- if (Right.isOneOf(tok::period, Keywords.kw_apostrophe) &&
- Keywords.isVerilogIdentifier(Left) && Left.getPreviousNonComment() &&
- Left.getPreviousNonComment()->is(Keywords.kw_tagged)) {
- return true;
- }
- // Don't add spaces between a casting type and the quote or repetition count
- // and the brace. The case of tagged union expressions is handled by the
- // previous rule.
- if ((Right.is(Keywords.kw_apostrophe) ||
- (Right.is(BK_BracedInit) && Right.is(tok::l_brace))) &&
- Left.isNoneOf(Keywords.kw_assign, Keywords.kw_unique) &&
- !Keywords.isVerilogWordOperator(Left) &&
- (Left.isOneOf(tok::r_square, tok::r_paren, tok::r_brace,
- tok::numeric_constant) ||
- Keywords.isWordLike(Left))) {
- return false;
- }
- // Don't add spaces in imports like `import foo::*;`.
- if ((Right.is(tok::star) && Left.is(tok::coloncolon)) ||
- (Left.is(tok::star) && Right.is(tok::semi))) {
- return false;
- }
- // Add space in attribute like `(* ASYNC_REG = "TRUE" *)`.
- if (Left.endsSequence(tok::star, tok::l_paren) && Right.is(tok::identifier))
- return true;
- // Add space before drive strength like in `wire (strong1, pull0)`.
- if (Right.is(tok::l_paren) && Right.is(TT_VerilogStrength))
- return true;
- // Don't add space in a streaming concatenation like `{>>{j}}`.
- if ((Left.is(tok::l_brace) &&
- Right.isOneOf(tok::lessless, tok::greatergreater)) ||
- (Left.endsSequence(tok::lessless, tok::l_brace) ||
- Left.endsSequence(tok::greatergreater, tok::l_brace))) {
- return false;
- }
- } else if (Style.isTableGen()) {
- // Avoid to connect [ and {. [{ is start token of multiline string.
- if (Left.is(tok::l_square) && Right.is(tok::l_brace))
- return true;
- if (Left.is(tok::r_brace) && Right.is(tok::r_square))
- return true;
- // Do not insert around colon in DAGArg and cond operator.
- if (Right.isOneOf(TT_TableGenDAGArgListColon,
- TT_TableGenDAGArgListColonToAlign) ||
- Left.isOneOf(TT_TableGenDAGArgListColon,
- TT_TableGenDAGArgListColonToAlign)) {
- return false;
- }
- if (Right.is(TT_TableGenCondOperatorColon))
- return false;
- if (Left.isOneOf(TT_TableGenDAGArgOperatorID,
- TT_TableGenDAGArgOperatorToBreak) &&
- Right.isNot(TT_TableGenDAGArgCloser)) {
- return true;
- }
- // Do not insert bang operators and consequent openers.
- if (Right.isOneOf(tok::l_paren, tok::less) &&
- Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator)) {
- return false;
- }
- // Trailing paste requires space before '{' or ':', the case in name values.
- // Not before ';', the case in normal values.
- if (Left.is(TT_TableGenTrailingPasteOperator) &&
- Right.isOneOf(tok::l_brace, tok::colon)) {
- return true;
- }
- // Otherwise paste operator does not prefer space around.
- if (Left.is(tok::hash) || Right.is(tok::hash))
- return false;
- // Sure not to connect after defining keywords.
- if (Keywords.isTableGenDefinition(Left))
- return true;
- }
-
- if (Left.is(TT_ImplicitStringLiteral))
- return Right.hasWhitespaceBefore();
- if (Line.Type == LT_ObjCMethodDecl) {
- if (Left.is(TT_ObjCMethodSpecifier))
- return Style.ObjCSpaceAfterMethodDeclarationPrefix;
- if (Left.is(tok::r_paren) && Left.isNot(TT_AttributeRParen) &&
- canBeObjCSelectorComponent(Right)) {
- // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
- // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
- // method declaration.
- return false;
- }
- }
- if (Line.Type == LT_ObjCProperty &&
- (Right.is(tok::equal) || Left.is(tok::equal))) {
- return false;
- }
-
- if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
- Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) {
- return true;
- }
- if (Left.is(tok::comma) && Right.isNot(TT_OverloadedOperatorLParen) &&
- // In an unexpanded macro call we only find the parentheses and commas
- // in a line; the commas and closing parenthesis do not require a space.
- (Left.Children.empty() || !Left.MacroParent)) {
- return true;
- }
- if (Right.is(tok::comma))
- return false;
- if (Right.is(TT_ObjCBlockLParen))
- return true;
- if (Right.is(TT_CtorInitializerColon))
- return Style.SpaceBeforeCtorInitializerColon;
- if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
- return false;
- if (Right.is(TT_RangeBasedForLoopColon) &&
- !Style.SpaceBeforeRangeBasedForLoopColon) {
- return false;
- }
- if (Left.is(TT_BitFieldColon)) {
- return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
- Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
- }
- if (Right.is(tok::colon)) {
- if (Right.is(TT_CaseLabelColon))
- return Style.SpaceBeforeCaseColon;
- if (Right.is(TT_GotoLabelColon))
- return false;
- // `private:` and `public:`.
- if (!Right.getNextNonComment())
- return false;
- if (Right.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
- return false;
- if (Left.is(tok::question))
- return false;
- if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
- return false;
- if (Right.is(TT_DictLiteral))
- return Style.SpacesInContainerLiterals;
- if (Right.is(TT_AttributeColon))
- return false;
- if (Right.is(TT_CSharpNamedArgumentColon))
- return false;
- if (Right.is(TT_GenericSelectionColon))
- return false;
- if (Right.is(TT_BitFieldColon)) {
- return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
- Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
- }
- return true;
- }
- // Do not merge "- -" into "--".
- if ((Left.isOneOf(tok::minus, tok::minusminus) &&
- Right.isOneOf(tok::minus, tok::minusminus)) ||
- (Left.isOneOf(tok::plus, tok::plusplus) &&
- Right.isOneOf(tok::plus, tok::plusplus))) {
- return true;
- }
- if (Left.is(TT_UnaryOperator)) {
- // Lambda captures allow for a lone &, so "&]" needs to be properly
- // handled.
- if (Left.is(tok::amp) && Right.is(tok::r_square))
- return Style.SpacesInSquareBrackets;
- if (Left.isNot(tok::exclaim))
- return false;
- if (Left.TokenText == "!")
- return Style.SpaceAfterLogicalNot;
- assert(Left.TokenText == "not");
- return Right.isOneOf(tok::coloncolon, TT_UnaryOperator) ||
- (Right.is(tok::l_paren) && Style.SpaceBeforeParensOptions.AfterNot);
- }
-
- // If the next token is a binary operator or a selector name, we have
- // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
- if (Left.is(TT_CastRParen)) {
- return Style.SpaceAfterCStyleCast ||
- Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
- }
-
- auto ShouldAddSpacesInAngles = [this, &Right]() {
- if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
- return true;
- if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
- return Right.hasWhitespaceBefore();
- return false;
- };
-
- if (Left.is(tok::greater) && Right.is(tok::greater)) {
- if (Style.isTextProto() ||
- (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) {
- return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
- }
- return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
- ((Style.Standard < FormatStyle::LS_Cpp11) ||
- ShouldAddSpacesInAngles());
- }
- if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
- Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
- (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) {
- return false;
- }
- if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
- Right.getPrecedence() == prec::Assignment) {
- return false;
- }
- if (Style.isJava() && Right.is(tok::coloncolon) &&
- Left.isOneOf(tok::identifier, tok::kw_this)) {
- return false;
- }
- if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) {
- // Generally don't remove existing spaces between an identifier and "::".
- // The identifier might actually be a macro name such as ALWAYS_INLINE. If
- // this turns out to be too lenient, add analysis of the identifier itself.
- return Right.hasWhitespaceBefore();
- }
- if (Right.is(tok::coloncolon) &&
- Left.isNoneOf(tok::l_brace, tok::comment, tok::l_paren)) {
- // Put a space between < and :: in vector< ::std::string >
- return (Left.is(TT_TemplateOpener) &&
- ((Style.Standard < FormatStyle::LS_Cpp11) ||
- ShouldAddSpacesInAngles())) ||
- Left.isNoneOf(tok::l_paren, tok::r_paren, tok::l_square,
- tok::kw___super, TT_TemplateOpener,
- TT_TemplateCloser) ||
- (Left.is(tok::l_paren) && Style.SpacesInParensOptions.Other);
- }
- if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
- return ShouldAddSpacesInAngles();
- if (Left.is(tok::r_paren) && Left.isNot(TT_TypeDeclarationParen) &&
- Right.is(TT_PointerOrReference) && Right.isOneOf(tok::amp, tok::ampamp)) {
- return true;
- }
- // Space before TT_StructuredBindingLSquare.
- if (Right.is(TT_StructuredBindingLSquare)) {
- return Left.isNoneOf(tok::amp, tok::ampamp) ||
- getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
- }
- // Space before & or && following a TT_StructuredBindingLSquare.
- if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
- Right.isOneOf(tok::amp, tok::ampamp)) {
- return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
- }
- if ((Right.is(TT_BinaryOperator) && Left.isNot(tok::l_paren)) ||
- (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
- Right.isNot(tok::r_paren))) {
- return true;
- }
- if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
- Left.MatchingParen &&
- Left.MatchingParen->is(TT_OverloadedOperatorLParen)) {
- return false;
- }
- if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
- Line.Type == LT_ImportStatement) {
- return true;
- }
- if (Right.is(TT_TrailingUnaryOperator))
- return false;
- if (Left.is(TT_RegexLiteral))
- return false;
- return spaceRequiredBetween(Line, Left, Right);
-}
-
-// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
-static bool isAllmanBrace(const FormatToken &Tok) {
- return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
- Tok.isNoneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
-}
-
-// Returns 'true' if 'Tok' is a function argument.
-static bool IsFunctionArgument(const FormatToken &Tok) {
- return Tok.MatchingParen && Tok.MatchingParen->Next &&
- Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren,
- tok::r_brace);
-}
-
-static bool
-isEmptyLambdaAllowed(const FormatToken &Tok,
- FormatStyle::ShortLambdaStyle ShortLambdaOption) {
- return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
-}
-
-static bool isAllmanLambdaBrace(const FormatToken &Tok) {
- return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
- Tok.isNoneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
-}
-
-bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line,
- const FormatToken &Right) const {
- if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0 &&
- (!Style.RemoveEmptyLinesInUnwrappedLines || &Right == Line.First)) {
- return true;
- }
-
- const FormatToken &Left = *Right.Previous;
-
- if (Style.BreakFunctionDefinitionParameters && Line.MightBeFunctionDecl &&
- Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
- Left.ParameterCount > 0) {
- return true;
- }
-
- // Ignores the first parameter as this will be handled separately by
- // BreakFunctionDefinitionParameters or AlignAfterOpenBracket.
- if (Style.BinPackParameters == FormatStyle::BPPS_AlwaysOnePerLine &&
- Line.MightBeFunctionDecl && !Left.opensScope() &&
- startsNextParameter(Right, Style)) {
- return true;
- }
-
- const auto *BeforeLeft = Left.Previous;
- const auto *AfterRight = Right.Next;
-
- if (Style.isCSharp()) {
- if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
- Style.BraceWrapping.AfterFunction) {
- return true;
- }
- if (Right.is(TT_CSharpNamedArgumentColon) ||
- Left.is(TT_CSharpNamedArgumentColon)) {
- return false;
- }
- if (Right.is(TT_CSharpGenericTypeConstraint))
- return true;
- if (AfterRight && AfterRight->is(TT_FatArrow) &&
- (Right.is(tok::numeric_constant) ||
- (Right.is(tok::identifier) && Right.TokenText == "_"))) {
- return true;
- }
-
- // Break after C# [...] and before public/protected/private/internal.
- if (Left.is(TT_AttributeRSquare) &&
- (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
- Right.is(Keywords.kw_internal))) {
- return true;
- }
- // Break between ] and [ but only when there are really 2 attributes.
- if (Left.is(TT_AttributeRSquare) && Right.is(TT_AttributeLSquare))
- return true;
- } else if (Style.isJavaScript()) {
- // FIXME: This might apply to other languages and token kinds.
- if (Right.is(tok::string_literal) && Left.is(tok::plus) && BeforeLeft &&
- BeforeLeft->is(tok::string_literal)) {
- return true;
- }
- if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
- BeforeLeft && BeforeLeft->is(tok::equal) &&
- Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
- tok::kw_const) &&
- // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
- // above.
- Line.First->isNoneOf(Keywords.kw_var, Keywords.kw_let)) {
- // Object literals on the top level of a file are treated as "enum-style".
- // Each key/value pair is put on a separate line, instead of bin-packing.
- return true;
- }
- if (Left.is(tok::l_brace) && Line.Level == 0 &&
- (Line.startsWith(tok::kw_enum) ||
- Line.startsWith(tok::kw_const, tok::kw_enum) ||
- Line.startsWith(tok::kw_export, tok::kw_enum) ||
- Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) {
- // JavaScript top-level enum key/value pairs are put on separate lines
- // instead of bin-packing.
- return true;
- }
- if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && BeforeLeft &&
- BeforeLeft->is(TT_FatArrow)) {
- // JS arrow function (=> {...}).
- switch (Style.AllowShortLambdasOnASingleLine) {
- case FormatStyle::SLS_All:
- return false;
- case FormatStyle::SLS_None:
- return true;
- case FormatStyle::SLS_Empty:
- return !Left.Children.empty();
- case FormatStyle::SLS_Inline:
- // allow one-lining inline (e.g. in function call args) and empty arrow
- // functions.
- return (Left.NestingLevel == 0 && Line.Level == 0) &&
- !Left.Children.empty();
- }
- llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
- }
-
- if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
- !Left.Children.empty()) {
- // Support AllowShortFunctionsOnASingleLine for JavaScript.
- if (Left.NestingLevel == 0 && Line.Level == 0)
- return !Style.AllowShortFunctionsOnASingleLine.Other;
-
- return !Style.AllowShortFunctionsOnASingleLine.Inline;
- }
- } else if (Style.isJava()) {
- if (Right.is(tok::plus) && Left.is(tok::string_literal) && AfterRight &&
- AfterRight->is(tok::string_literal)) {
- return true;
- }
- } else if (Style.isVerilog()) {
- // Break between assignments.
- if (Left.is(TT_VerilogAssignComma))
- return true;
- // Break between ports of different types.
- if (Left.is(TT_VerilogTypeComma))
- return true;
- // Break between ports in a module instantiation and after the parameter
- // list.
- if (Style.VerilogBreakBetweenInstancePorts &&
- (Left.is(TT_VerilogInstancePortComma) ||
- (Left.is(tok::r_paren) && Keywords.isVerilogIdentifier(Right) &&
- Left.MatchingParen &&
- Left.MatchingParen->is(TT_VerilogInstancePortLParen)))) {
- return true;
- }
- // Break after labels. In Verilog labels don't have the 'case' keyword, so
- // it is hard to identify them in UnwrappedLineParser.
- if (!Keywords.isVerilogBegin(Right) && Keywords.isVerilogEndOfLabel(Left))
- return true;
- } else if (Style.BreakAdjacentStringLiterals &&
- (IsCpp || Style.isProto() || Style.isTableGen())) {
- if (Left.isStringLiteral() && Right.isStringLiteral())
- return true;
- }
-
- // Basic JSON newline processing.
- if (Style.isJson()) {
- // Always break after a JSON record opener.
- // {
- // }
- if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
- return true;
- // Always break after a JSON array opener based on BreakArrays.
- if ((Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
- Right.isNot(tok::r_square)) ||
- Left.is(tok::comma)) {
- if (Right.is(tok::l_brace))
- return true;
- // scan to the right if an we see an object or an array inside
- // then break.
- for (const auto *Tok = &Right; Tok; Tok = Tok->Next) {
- if (Tok->isOneOf(tok::l_brace, tok::l_square))
- return true;
- if (Tok->isOneOf(tok::r_brace, tok::r_square))
- break;
- }
- return Style.BreakArrays;
- }
- } else if (Style.isTableGen()) {
- // Break the comma in side cond operators.
- // !cond(case1:1,
- // case2:0);
- if (Left.is(TT_TableGenCondOperatorComma))
- return true;
- if (Left.is(TT_TableGenDAGArgOperatorToBreak) &&
- Right.isNot(TT_TableGenDAGArgCloser)) {
- return true;
- }
- if (Left.is(TT_TableGenDAGArgListCommaToBreak))
- return true;
- if (Right.is(TT_TableGenDAGArgCloser) && Right.MatchingParen &&
- Right.MatchingParen->is(TT_TableGenDAGArgOpenerToBreak) &&
- &Left != Right.MatchingParen->Next) {
- // Check to avoid empty DAGArg such as (ins).
- return Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll;
- }
- }
-
- if (Line.startsWith(tok::kw_asm) && Right.is(TT_InlineASMColon) &&
- Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always) {
- return true;
- }
-
- // If the last token before a '}', ']', or ')' is a comma or a trailing
- // comment, the intention is to insert a line break after it in order to make
- // shuffling around entries easier. Import statements, especially in
- // JavaScript, can be an exception to this rule.
- if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
- const FormatToken *BeforeClosingBrace = nullptr;
- if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
- (Style.isJavaScript() && Left.is(tok::l_paren))) &&
- Left.isNot(BK_Block) && Left.MatchingParen) {
- BeforeClosingBrace = Left.MatchingParen->Previous;
- } else if (Right.MatchingParen &&
- (Right.MatchingParen->isOneOf(tok::l_brace,
- TT_ArrayInitializerLSquare) ||
- (Style.isJavaScript() &&
- Right.MatchingParen->is(tok::l_paren)))) {
- BeforeClosingBrace = &Left;
- }
- if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
- BeforeClosingBrace->isTrailingComment())) {
- return true;
- }
- }
-
- if (Right.is(tok::comment)) {
- return Left.isNoneOf(BK_BracedInit, TT_CtorInitializerColon) &&
- Right.NewlinesBefore > 0 && Right.HasUnescapedNewline;
- }
- if (Left.isTrailingComment())
- return true;
- if (Left.IsUnterminatedLiteral)
- return true;
-
- if (BeforeLeft && BeforeLeft->is(tok::lessless) &&
- Left.is(tok::string_literal) && Right.is(tok::lessless) && AfterRight &&
- AfterRight->is(tok::string_literal)) {
- return Right.NewlinesBefore > 0;
- }
-
- if (Right.is(TT_RequiresClause)) {
- switch (Style.RequiresClausePosition) {
- case FormatStyle::RCPS_OwnLine:
- case FormatStyle::RCPS_OwnLineWithBrace:
- case FormatStyle::RCPS_WithFollowing:
- return true;
- default:
- break;
- }
- }
- // Can break after template<> declaration
- if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
- Left.MatchingParen->NestingLevel == 0) {
- // Put concepts on the next line e.g.
- // template<typename T>
- // concept ...
- if (Right.is(tok::kw_concept))
- return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
- return Style.BreakTemplateDeclarations == FormatStyle::BTDS_Yes ||
- (Style.BreakTemplateDeclarations == FormatStyle::BTDS_Leave &&
- Right.NewlinesBefore > 0);
- }
- if (Left.ClosesRequiresClause) {
- switch (Style.RequiresClausePosition) {
- case FormatStyle::RCPS_OwnLine:
- case FormatStyle::RCPS_WithPreceding:
- return Right.isNot(tok::semi);
- case FormatStyle::RCPS_OwnLineWithBrace:
- return Right.isNoneOf(tok::semi, tok::l_brace);
- default:
- break;
- }
- }
- if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
- if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
- (Left.is(TT_CtorInitializerComma) ||
- Right.is(TT_CtorInitializerColon))) {
- return true;
- }
-
- if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
- Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) {
- return true;
- }
-
- if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterComma &&
- Left.is(TT_CtorInitializerComma)) {
- return true;
- }
- }
- if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
- Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
- Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) {
- return true;
- }
- if (Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly) {
- if ((Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon ||
- Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) &&
- Right.is(TT_CtorInitializerColon)) {
- return true;
- }
-
- if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
- Left.is(TT_CtorInitializerColon)) {
- return true;
- }
- }
- // Break only if we have multiple inheritance.
- if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
- Right.is(TT_InheritanceComma)) {
- return true;
- }
- if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
- Left.is(TT_InheritanceComma)) {
- return true;
- }
- if (Right.is(tok::string_literal) && Right.TokenText.starts_with("R\"")) {
- // Multiline raw string literals are special wrt. line breaks. The author
- // has made a deliberate choice and might have aligned the contents of the
- // string literal accordingly. Thus, we try keep existing line breaks.
- return Right.IsMultiline && Right.NewlinesBefore > 0;
- }
- if ((Left.is(tok::l_brace) ||
- (Left.is(tok::less) && BeforeLeft && BeforeLeft->is(tok::equal))) &&
- Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
- // Don't put enums or option definitions onto single lines in protocol
- // buffers.
- return true;
- }
- if (Right.is(TT_InlineASMBrace))
- return Right.HasUnescapedNewline;
-
- if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
- auto *FirstNonComment = Line.getFirstNonComment();
- bool AccessSpecifier =
- FirstNonComment && (FirstNonComment->is(Keywords.kw_internal) ||
- FirstNonComment->isAccessSpecifierKeyword());
-
- if (Style.BraceWrapping.AfterEnum) {
- if (Line.startsWith(tok::kw_enum) ||
- Line.startsWith(tok::kw_typedef, tok::kw_enum) ||
- Line.startsWith(tok::kw_export, tok::kw_enum)) {
- return true;
- }
- // Ensure BraceWrapping for `public enum A {`.
- if (AccessSpecifier && FirstNonComment->Next &&
- FirstNonComment->Next->is(tok::kw_enum)) {
- return true;
- }
- }
-
- // Ensure BraceWrapping for `public interface A {`.
- if (Style.BraceWrapping.AfterClass &&
- ((AccessSpecifier && FirstNonComment->Next &&
- FirstNonComment->Next->is(Keywords.kw_interface)) ||
- Line.startsWith(Keywords.kw_interface))) {
- return true;
- }
-
- // Don't attempt to interpret record return types as records.
- if (Right.isNot(TT_FunctionLBrace)) {
- return Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Never &&
- ((Line.startsWith(tok::kw_class) &&
- Style.BraceWrapping.AfterClass) ||
- (Line.startsWith(tok::kw_struct) &&
- Style.BraceWrapping.AfterStruct) ||
- (Line.startsWith(tok::kw_union) &&
- Style.BraceWrapping.AfterUnion));
- }
- }
-
- if (Left.is(TT_ObjCBlockLBrace) &&
- Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
- return true;
- }
-
- // Ensure wrapping after __attribute__((XX)) and @interface etc.
- if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
- Right.is(TT_ObjCDecl)) {
- return true;
- }
-
- if (Left.is(TT_LambdaLBrace)) {
- if (IsFunctionArgument(Left) &&
- Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) {
- return false;
- }
-
- if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
- Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
- (!Left.Children.empty() &&
- Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) {
- return true;
- }
- }
-
- if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
- (Left.isPointerOrReference() || Left.is(TT_TemplateCloser))) {
- return true;
- }
-
- // Put multiple Java annotation on a new line.
- if ((Style.isJava() || Style.isJavaScript()) &&
- Left.is(TT_LeadingJavaAnnotation) &&
- Right.isNoneOf(TT_LeadingJavaAnnotation, tok::l_paren) &&
- (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) {
- return true;
- }
-
- if (Right.is(TT_ProtoExtensionLSquare))
- return true;
-
- // In text proto instances if a submessage contains at least 2 entries and at
- // least one of them is a submessage, like A { ... B { ... } ... },
- // put all of the entries of A on separate lines by forcing the selector of
- // the submessage B to be put on a newline.
- //
- // Example: these can stay on one line:
- // a { scalar_1: 1 scalar_2: 2 }
- // a { b { key: value } }
- //
- // and these entries need to be on a new line even if putting them all in one
- // line is under the column limit:
- // a {
- // scalar: 1
- // b { key: value }
- // }
- //
- // We enforce this by breaking before a submessage field that has previous
- // siblings, *and* breaking before a field that follows a submessage field.
- //
- // Be careful to exclude the case [proto.ext] { ... } since the `]` is
- // the TT_SelectorName there, but we don't want to break inside the brackets.
- //
- // Another edge case is @submessage { key: value }, which is a common
- // substitution placeholder. In this case we want to keep `@` and `submessage`
- // together.
- //
- // We ensure elsewhere that extensions are always on their own line.
- if (Style.isProto() && Right.is(TT_SelectorName) &&
- Right.isNot(tok::r_square) && AfterRight) {
- // Keep `@submessage` together in:
- // @submessage { key: value }
- if (Left.is(tok::at))
- return false;
- // Look for the scope opener after selector in cases like:
- // selector { ...
- // selector: { ...
- // selector: @base { ...
- const auto *LBrace = AfterRight;
- if (LBrace && LBrace->is(tok::colon)) {
- LBrace = LBrace->Next;
- if (LBrace && LBrace->is(tok::at)) {
- LBrace = LBrace->Next;
- if (LBrace)
- LBrace = LBrace->Next;
- }
- }
- if (LBrace &&
- // The scope opener is one of {, [, <:
- // selector { ... }
- // selector [ ... ]
- // selector < ... >
- //
- // In case of selector { ... }, the l_brace is TT_DictLiteral.
- // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
- // so we check for immediately following r_brace.
- ((LBrace->is(tok::l_brace) &&
- (LBrace->is(TT_DictLiteral) ||
- (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
- LBrace->isOneOf(TT_ArrayInitializerLSquare, tok::less))) {
- // If Left.ParameterCount is 0, then this submessage entry is not the
- // first in its parent submessage, and we want to break before this entry.
- // If Left.ParameterCount is greater than 0, then its parent submessage
- // might contain 1 or more entries and we want to break before this entry
- // if it contains at least 2 entries. We deal with this case later by
- // detecting and breaking before the next entry in the parent submessage.
- if (Left.ParameterCount == 0)
- return true;
- // However, if this submessage is the first entry in its parent
- // submessage, Left.ParameterCount might be 1 in some cases.
- // We deal with this case later by detecting an entry
- // following a closing paren of this submessage.
- }
-
- // If this is an entry immediately following a submessage, it will be
- // preceded by a closing paren of that submessage, like in:
- // left---. .---right
- // v v
- // sub: { ... } key: value
- // If there was a comment between `}` an `key` above, then `key` would be
- // put on a new line anyways.
- if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
- return true;
- }
-
- if (Style.BreakAfterAttributes == FormatStyle::ABS_LeaveAll &&
- Left.is(TT_AttributeRSquare) && Right.NewlinesBefore > 0) {
- Line.ReturnTypeWrapped = true;
- return true;
- }
-
- return false;
-}
-
-bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
- const FormatToken &Right) const {
- const FormatToken &Left = *Right.Previous;
- // Language-specific stuff.
- if (Style.isCSharp()) {
- if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
- Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) {
- return false;
- }
- // Only break after commas for generic type constraints.
- if (Line.First->is(TT_CSharpGenericTypeConstraint))
- return Left.is(TT_CSharpGenericTypeConstraintComma);
- // Keep nullable operators attached to their identifiers.
- if (Right.is(TT_CSharpNullable))
- return false;
- } else if (Style.isJava()) {
- if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
- Keywords.kw_implements)) {
- return false;
- }
- if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
- Keywords.kw_implements)) {
- return true;
- }
- } else if (Style.isJavaScript()) {
- const FormatToken *NonComment = Right.getPreviousNonComment();
- if (NonComment &&
- (NonComment->isAccessSpecifierKeyword() ||
- NonComment->isOneOf(
- tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
- tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
- tok::kw_static, Keywords.kw_readonly, Keywords.kw_override,
- Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set,
- Keywords.kw_async, Keywords.kw_await))) {
- return false; // Otherwise automatic semicolon insertion would trigger.
- }
- if (Right.NestingLevel == 0 &&
- (Left.Tok.getIdentifierInfo() ||
- Left.isOneOf(tok::r_square, tok::r_paren)) &&
- Right.isOneOf(tok::l_square, tok::l_paren)) {
- return false; // Otherwise automatic semicolon insertion would trigger.
- }
- if (NonComment && NonComment->is(tok::identifier) &&
- NonComment->TokenText == "asserts") {
- return false;
- }
- if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
- return false;
- if (Left.is(TT_JsTypeColon))
- return true;
- // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
- if (Left.is(tok::exclaim) && Right.is(tok::colon))
- return false;
- // Look for is type annotations like:
- // function f(): a is B { ... }
- // Do not break before is in these cases.
- if (Right.is(Keywords.kw_is)) {
- const FormatToken *Next = Right.getNextNonComment();
- // If `is` is followed by a colon, it's likely that it's a dict key, so
- // ignore it for this check.
- // For example this is common in Polymer:
- // Polymer({
- // is: 'name',
- // ...
- // });
- if (!Next || Next->isNot(tok::colon))
- return false;
- }
- if (Left.is(Keywords.kw_in))
- return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
- if (Right.is(Keywords.kw_in))
- return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
- if (Right.is(Keywords.kw_as))
- return false; // must not break before as in 'x as type' casts
- if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
- // extends and infer can appear as keywords in conditional types:
- // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
- // do not break before them, as the expressions are subject to ASI.
- return false;
- }
- if (Left.is(Keywords.kw_as))
- return true;
- if (Left.is(TT_NonNullAssertion))
- return true;
- if (Left.is(Keywords.kw_declare) &&
- Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
- Keywords.kw_function, tok::kw_class, tok::kw_enum,
- Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
- Keywords.kw_let, tok::kw_const)) {
- // See grammar for 'declare' statements at:
- // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
- return false;
- }
- if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
- Right.isOneOf(tok::identifier, tok::string_literal)) {
- return false; // must not break in "module foo { ...}"
- }
- if (Right.is(TT_TemplateString) && Right.closesScope())
- return false;
- // Don't split tagged template literal so there is a break between the tag
- // identifier and template string.
- if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
- return false;
- if (Left.is(TT_TemplateString) && Left.opensScope())
- return true;
- } else if (Style.isTableGen()) {
- // Avoid to break after "def", "class", "let" and so on.
- if (Keywords.isTableGenDefinition(Left))
- return false;
- // Avoid to break after '(' in the cases that is in bang operators.
- if (Right.is(tok::l_paren)) {
- return Left.isNoneOf(TT_TableGenBangOperator, TT_TableGenCondOperator,
- TT_TemplateCloser);
- }
- // Avoid to break between the value and its suffix part.
- if (Left.is(TT_TableGenValueSuffix))
- return false;
- // Avoid to break around paste operator.
- if (Left.is(tok::hash) || Right.is(tok::hash))
- return false;
- if (Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator))
- return false;
- }
-
- // We can break before an r_brace if there was a break after the matching
- // l_brace, which is tracked by BreakBeforeClosingBrace, or if we are in a
- // block-indented initialization list.
- if (Right.is(tok::r_brace)) {
- return Right.MatchingParen && (Right.MatchingParen->is(BK_Block) ||
- (Right.isBlockIndentedInitRBrace(Style)));
- }
-
- // We can break before r_paren if we're in a block indented context or
- // a control statement with an explicit style option.
- if (Right.is(tok::r_paren)) {
- if (!Right.MatchingParen)
- return false;
- auto Next = Right.Next;
- if (Next && Next->is(tok::r_paren))
- Next = Next->Next;
- if (Next && Next->is(tok::l_paren))
- return false;
- const FormatToken *Previous = Right.MatchingParen->Previous;
- if (!Previous)
- return false;
- if (Previous->isIf())
- return Style.BreakBeforeCloseBracketIf;
- if (Previous->isLoop(Style))
- return Style.BreakBeforeCloseBracketLoop;
- if (Previous->is(tok::kw_switch))
- return Style.BreakBeforeCloseBracketSwitch;
- return Style.BreakBeforeCloseBracketFunction;
- }
-
- if (Left.isOneOf(tok::r_paren, TT_TrailingAnnotation) &&
- Right.is(TT_TrailingAnnotation) &&
- Style.BreakBeforeCloseBracketFunction) {
- return false;
- }
-
- if (Right.is(TT_TemplateCloser))
- return Style.BreakBeforeTemplateCloser;
-
- if (Left.isOneOf(tok::at, tok::objc_interface))
- return false;
- if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
- return Right.isNot(tok::l_paren);
- if (Right.is(TT_PointerOrReference)) {
- return Line.IsMultiVariableDeclStmt ||
- (getTokenPointerOrReferenceAlignment(Right) ==
- FormatStyle::PAS_Right &&
- !(Right.Next &&
- Right.Next->isOneOf(TT_FunctionDeclarationName, tok::kw_const)));
- }
- if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
- TT_ClassHeadName, TT_QtProperty, tok::kw_operator)) {
- return true;
- }
- if (Left.is(TT_PointerOrReference))
- return false;
- if (Right.isTrailingComment()) {
- // We rely on MustBreakBefore being set correctly here as we should not
- // change the "binding" behavior of a comment.
- // The first comment in a braced lists is always interpreted as belonging to
- // the first list element. Otherwise, it should be placed outside of the
- // list.
- return Left.is(BK_BracedInit) ||
- (Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
- Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
- }
- if (Left.is(tok::question) && Right.is(tok::colon))
- return false;
- if (Right.isOneOf(TT_ConditionalExpr, tok::question))
- return Style.BreakBeforeTernaryOperators;
- if (Left.isOneOf(TT_ConditionalExpr, tok::question))
- return !Style.BreakBeforeTernaryOperators;
- if (Left.is(TT_InheritanceColon))
- return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
- if (Right.is(TT_InheritanceColon))
- return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
- // When the method parameter has no name, allow breaking before the colon.
- if (Right.is(TT_ObjCMethodExpr) && Right.isNot(tok::r_square) &&
- Left.isNot(TT_SelectorName)) {
- return true;
- }
-
- if (Right.is(tok::colon) &&
- Right.isNoneOf(TT_CtorInitializerColon, TT_InlineASMColon,
- TT_BitFieldColon)) {
- return false;
- }
- if (Left.is(tok::colon) && Left.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
- return true;
- if (Left.is(tok::colon) && Left.is(TT_DictLiteral)) {
- if (Style.isProto()) {
- if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
- return false;
- // Prevent cases like:
- //
- // submessage:
- // { key: valueeeeeeeeeeee }
- //
- // when the snippet does not fit into one line.
- // Prefer:
- //
- // submessage: {
- // key: valueeeeeeeeeeee
- // }
- //
- // instead, even if it is longer by one line.
- //
- // Note that this allows the "{" to go over the column limit
- // when the column limit is just between ":" and "{", but that does
- // not happen too often and alternative formattings in this case are
- // not much better.
- //
- // The code covers the cases:
- //
- // submessage: { ... }
- // submessage: < ... >
- // repeated: [ ... ]
- if ((Right.isOneOf(tok::l_brace, tok::less) &&
- Right.is(TT_DictLiteral)) ||
- Right.is(TT_ArrayInitializerLSquare)) {
- return false;
- }
- }
- return true;
- }
- if (Right.is(tok::r_square) && Right.MatchingParen &&
- Right.MatchingParen->is(TT_ProtoExtensionLSquare)) {
- return false;
- }
- if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
- Right.Next->is(TT_ObjCMethodExpr))) {
- return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
- }
- if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
- return true;
- if (Right.is(tok::kw_concept))
- return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
- if (Right.is(TT_RequiresClause))
- return true;
- if (Left.ClosesTemplateDeclaration) {
- return Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
- Right.NewlinesBefore > 0;
- }
- if (Left.is(TT_FunctionAnnotationRParen))
- return true;
- if (Left.ClosesRequiresClause)
- return true;
- if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
- TT_OverloadedOperator)) {
- return false;
- }
- if (Left.is(TT_RangeBasedForLoopColon))
- return true;
- if (Right.is(TT_RangeBasedForLoopColon))
- return false;
- if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
- return true;
- if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
- (Left.is(tok::less) && Right.is(tok::less))) {
- return false;
- }
- if (Right.is(TT_BinaryOperator) &&
- Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
- (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
- Right.getPrecedence() != prec::Assignment)) {
- return true;
- }
- if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator, tok::kw_operator))
- return false;
- if (Left.is(tok::equal) && Right.isNoneOf(tok::kw_default, tok::kw_delete) &&
- Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) {
- return false;
- }
- if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
- Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
- return false;
- }
- if (Left.is(TT_AttributeLParen) ||
- (Left.is(tok::l_paren) && Left.is(TT_TypeDeclarationParen))) {
- return false;
- }
- if (Left.is(tok::l_paren) && Left.Previous &&
- (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) {
- return false;
- }
- if (Right.is(TT_ImplicitStringLiteral))
- return false;
-
- if (Right.is(tok::r_square) && Right.MatchingParen &&
- Right.MatchingParen->is(TT_LambdaLSquare)) {
- return false;
- }
-
- // Allow breaking after a trailing annotation, e.g. after a method
- // declaration.
- if (Left.is(TT_TrailingAnnotation)) {
- return Right.isNoneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
- tok::less, tok::coloncolon);
- }
-
- if (Right.isAttribute())
- return true;
-
- if (Right.is(TT_AttributeLSquare)) {
- assert(Left.isNot(tok::l_square));
- return true;
- }
-
- if (Left.is(tok::identifier) && Right.is(tok::string_literal))
- return true;
-
- if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
- return true;
-
- if (Left.is(TT_CtorInitializerColon)) {
- return (Style.BreakConstructorInitializers ==
- FormatStyle::BCIS_AfterColon ||
- Style.BreakConstructorInitializers ==
- FormatStyle::BCIS_AfterComma) &&
- (!Right.isTrailingComment() || Right.NewlinesBefore > 0);
- }
- if (Right.is(TT_CtorInitializerColon)) {
- return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon &&
- Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterComma;
- }
- if (Left.is(TT_CtorInitializerComma) &&
- Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
- return false;
- }
- if (Right.is(TT_CtorInitializerComma) &&
- Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
- return true;
- }
- if (Left.is(TT_InheritanceComma) &&
- Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
- return false;
- }
- if (Right.is(TT_InheritanceComma) &&
- Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
- return true;
- }
- if (Left.is(TT_ArrayInitializerLSquare))
- return true;
- if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
- return true;
- if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
- Left.isNoneOf(tok::arrowstar, tok::lessless) &&
- Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
- (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
- Left.getPrecedence() == prec::Assignment)) {
- return true;
- }
- if (Left.is(TT_AttributeLSquare) && Right.is(tok::l_square)) {
- assert(Right.isNot(TT_AttributeLSquare));
- return false;
- }
- if (Left.is(tok::r_square) && Right.is(TT_AttributeRSquare)) {
- assert(Left.isNot(TT_AttributeRSquare));
- return false;
- }
-
- auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
- if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
- if (isAllmanLambdaBrace(Left))
- return !isEmptyLambdaAllowed(Left, ShortLambdaOption);
- if (isAllmanLambdaBrace(Right))
- return !isEmptyLambdaAllowed(Right, ShortLambdaOption);
- }
-
- if (Right.is(tok::kw_noexcept) && Right.is(TT_TrailingAnnotation)) {
- switch (Style.AllowBreakBeforeNoexceptSpecifier) {
- case FormatStyle::BBNSS_Never:
- return false;
- case FormatStyle::BBNSS_Always:
- return true;
- case FormatStyle::BBNSS_OnlyWithParen:
- return Right.Next && Right.Next->is(tok::l_paren);
- }
- }
-
- return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
- tok::kw_class, tok::kw_struct, tok::comment) ||
- Right.isMemberAccess() ||
- Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
- tok::colon, tok::l_square, tok::at) ||
- (Left.is(tok::r_paren) &&
- Right.isOneOf(tok::identifier, tok::kw_const)) ||
- (Left.is(tok::l_paren) && Right.isNot(tok::r_paren)) ||
- (Left.is(TT_TemplateOpener) && Right.isNot(TT_TemplateCloser));
-}
-
-void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
- llvm::errs() << "AnnotatedTokens(L=" << Line.Level << ", P=" << Line.PPLevel
- << ", T=" << Line.Type << ", C=" << Line.IsContinuation
- << "):\n";
- const FormatToken *Tok = Line.First;
- while (Tok) {
- llvm::errs() << " I=" << Tok->IndentLevel << " M=" << Tok->MustBreakBefore
- << " C=" << Tok->CanBreakBefore
- << " T=" << getTokenTypeName(Tok->getType())
- << " S=" << Tok->SpacesRequiredBefore
- << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
- << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
- << " Name=" << Tok->Tok.getName() << " N=" << Tok->NestingLevel
- << " L=" << Tok->TotalLength
- << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
- for (prec::Level LParen : Tok->FakeLParens)
- llvm::errs() << LParen << "/";
- llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
- llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
- llvm::errs() << " Text='" << Tok->TokenText << "'\n";
- if (!Tok->Next)
- assert(Tok == Line.Last);
- Tok = Tok->Next;
- }
- llvm::errs() << "----\n";
-}
-
-FormatStyle::PointerAlignmentStyle
-TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
- assert(Reference.isOneOf(tok::amp, tok::ampamp));
- switch (Style.ReferenceAlignment) {
- case FormatStyle::RAS_Pointer:
- return Style.PointerAlignment;
- case FormatStyle::RAS_Left:
- return FormatStyle::PAS_Left;
- case FormatStyle::RAS_Right:
- return FormatStyle::PAS_Right;
- case FormatStyle::RAS_Middle:
- return FormatStyle::PAS_Middle;
- }
- assert(0); //"Unhandled value of ReferenceAlignment"
- return Style.PointerAlignment;
-}
-
-FormatStyle::PointerAlignmentStyle
-TokenAnnotator::getTokenPointerOrReferenceAlignment(
- const FormatToken &PointerOrReference) const {
- if (PointerOrReference.isOneOf(tok::amp, tok::ampamp))
- return getTokenReferenceAlignment(PointerOrReference);
- assert(PointerOrReference.is(tok::star));
- return Style.PointerAlignment;
-}
-
-} // namespace format
-} // namespace clang
+//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file implements a token annotator, i.e. creates
+/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
+///
+//===----------------------------------------------------------------------===//
+
+#include "TokenAnnotator.h"
+#include "FormatToken.h"
+#include "clang/Basic/TokenKinds.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "format-token-annotator"
+
+namespace clang {
+namespace format {
+
+static bool mustBreakAfterAttributes(const FormatToken &Tok,
+ const FormatStyle &Style) {
+ switch (Style.BreakAfterAttributes) {
+ case FormatStyle::ABS_Always:
+ return true;
+ case FormatStyle::ABS_Never:
+ return false;
+ default: // ABS_Leave and ABS_LeaveAll
+ return Tok.NewlinesBefore > 0;
+ }
+}
+
+namespace {
+
+/// Returns \c true if the line starts with a token that can start a statement
+/// with an initializer.
+static bool startsWithInitStatement(const AnnotatedLine &Line) {
+ return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
+ Line.startsWith(tok::kw_switch);
+}
+
+/// Returns \c true if the token can be used as an identifier in
+/// an Objective-C \c \@selector, \c false otherwise.
+///
+/// Because getFormattingLangOpts() always lexes source code as
+/// Objective-C++, C++ keywords like \c new and \c delete are
+/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
+///
+/// For Objective-C and Objective-C++, both identifiers and keywords
+/// are valid inside @selector(...) (or a macro which
+/// invokes @selector(...)). So, we allow treat any identifier or
+/// keyword as a potential Objective-C selector component.
+static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
+ return Tok.Tok.getIdentifierInfo();
+}
+
+/// With `Left` being '(', check if we're at either `[...](` or
+/// `[...]<...>(`, where the [ opens a lambda capture list.
+// FIXME: this doesn't cover attributes/constraints before the l_paren.
+static bool isLambdaParameterList(const FormatToken *Left) {
+ // Skip <...> if present.
+ if (Left->Previous && Left->Previous->is(tok::greater) &&
+ Left->Previous->MatchingParen &&
+ Left->Previous->MatchingParen->is(TT_TemplateOpener)) {
+ Left = Left->Previous->MatchingParen;
+ }
+
+ // Check for `[...]`.
+ return Left->Previous && Left->Previous->is(tok::r_square) &&
+ Left->Previous->MatchingParen &&
+ Left->Previous->MatchingParen->is(TT_LambdaLSquare);
+}
+
+/// Returns \c true if the token is followed by a boolean condition, \c false
+/// otherwise.
+static bool isKeywordWithCondition(const FormatToken &Tok) {
+ return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
+ tok::kw_constexpr, tok::kw_catch);
+}
+
+/// Returns \c true if the token starts a C++ attribute, \c false otherwise.
+static bool isCppAttribute(bool IsCpp, const FormatToken &Tok) {
+ if (!IsCpp || !Tok.startsSequence(tok::l_square, tok::l_square))
+ return false;
+ // The first square bracket is part of an ObjC array literal
+ if (Tok.Previous && Tok.Previous->is(tok::at))
+ return false;
+ const FormatToken *AttrTok = Tok.Next->Next;
+ if (!AttrTok)
+ return false;
+ // C++17 '[[using ns: foo, bar(baz, blech)]]'
+ // We assume nobody will name an ObjC variable 'using'.
+ if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
+ return true;
+ if (AttrTok->isNot(tok::identifier))
+ return false;
+ while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
+ // ObjC message send. We assume nobody will use : in a C++11 attribute
+ // specifier parameter, although this is technically valid:
+ // [[foo(:)]].
+ if (AttrTok->is(tok::colon) ||
+ AttrTok->startsSequence(tok::identifier, tok::identifier) ||
+ AttrTok->startsSequence(tok::r_paren, tok::identifier)) {
+ return false;
+ }
+ if (AttrTok->is(tok::ellipsis))
+ return true;
+ AttrTok = AttrTok->Next;
+ }
+ return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
+}
+
+/// A parser that gathers additional information about tokens.
+///
+/// The \c TokenAnnotator tries to match parenthesis and square brakets and
+/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
+/// into template parameter lists.
+class AnnotatingParser {
+public:
+ AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
+ const AdditionalKeywords &Keywords,
+ SmallVector<ScopeType> &Scopes)
+ : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
+ IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
+ Keywords(Keywords), Scopes(Scopes), TemplateDeclarationDepth(0) {
+ Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
+ resetTokenMetadata();
+ }
+
+private:
+ ScopeType getScopeType(const FormatToken &Token) const {
+ switch (Token.getType()) {
+ case TT_ClassLBrace:
+ case TT_StructLBrace:
+ case TT_UnionLBrace:
+ return ST_Class;
+ case TT_CompoundRequirementLBrace:
+ return ST_CompoundRequirement;
+ default:
+ return ST_Other;
+ }
+ }
+
+ bool parseAngle() {
+ if (!CurrentToken)
+ return false;
+
+ auto *Left = CurrentToken->Previous; // The '<'.
+ if (!Left)
+ return false;
+
+ if (NonTemplateLess.count(Left) > 0)
+ return false;
+
+ const auto *BeforeLess = Left->Previous;
+
+ if (BeforeLess) {
+ if (BeforeLess->Tok.isLiteral())
+ return false;
+ if (BeforeLess->is(tok::r_brace))
+ return false;
+ if (BeforeLess->is(tok::r_paren) && Contexts.size() > 1 &&
+ !(BeforeLess->MatchingParen &&
+ BeforeLess->MatchingParen->is(TT_OverloadedOperatorLParen))) {
+ return false;
+ }
+ if (BeforeLess->is(tok::kw_operator) && CurrentToken->is(tok::l_paren))
+ return false;
+ }
+
+ Left->ParentBracket = Contexts.back().ContextKind;
+ ScopedContextCreator ContextCreator(*this, tok::less, 12);
+ Contexts.back().IsExpression = false;
+
+ // If there's a template keyword before the opening angle bracket, this is a
+ // template parameter, not an argument.
+ if (BeforeLess && BeforeLess->isNot(tok::kw_template))
+ Contexts.back().ContextType = Context::TemplateArgument;
+
+ if (Style.isJava() && CurrentToken->is(tok::question))
+ next();
+
+ for (bool SeenTernaryOperator = false, MaybeAngles = true; CurrentToken;) {
+ const auto &ParentContext = Contexts[Contexts.size() - 2];
+ const bool InExpr = ParentContext.IsExpression;
+ if (CurrentToken->is(tok::greater)) {
+ const auto *Next = CurrentToken->Next;
+ if (CurrentToken->isNot(TT_TemplateCloser)) {
+ // Try to do a better job at looking for ">>" within the condition of
+ // a statement. Conservatively insert spaces between consecutive ">"
+ // tokens to prevent splitting right shift operators and potentially
+ // altering program semantics. This check is overly conservative and
+ // will prevent spaces from being inserted in select nested template
+ // parameter cases, but should not alter program semantics.
+ if (Next && Next->is(tok::greater) &&
+ Left->ParentBracket != tok::less &&
+ CurrentToken->getStartOfNonWhitespace() ==
+ Next->getStartOfNonWhitespace().getLocWithOffset(-1)) {
+ return false;
+ }
+ if (InExpr && SeenTernaryOperator &&
+ (!Next || Next->isNoneOf(tok::l_paren, tok::l_brace))) {
+ return false;
+ }
+ if (!MaybeAngles)
+ return false;
+ if (ParentContext.InStaticAssertFirstArgument && Next &&
+ Next->isOneOf(tok::minus, tok::identifier)) {
+ return false;
+ }
+ }
+ Left->MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = Left;
+ // In TT_Proto, we must distignuish between:
+ // map<key, value>
+ // msg < item: data >
+ // msg: < item: data >
+ // In TT_TextProto, map<key, value> does not occur.
+ if (Style.isTextProto() ||
+ (Style.Language == FormatStyle::LK_Proto && BeforeLess &&
+ BeforeLess->isOneOf(TT_SelectorName, TT_DictLiteral))) {
+ CurrentToken->setType(TT_DictLiteral);
+ } else {
+ CurrentToken->setType(TT_TemplateCloser);
+ CurrentToken->Tok.setLength(1);
+ }
+ if (Next && Next->Tok.isLiteral())
+ return false;
+ next();
+ return true;
+ }
+ if (BeforeLess && BeforeLess->is(TT_TemplateName)) {
+ next();
+ continue;
+ }
+ if (CurrentToken->is(tok::question) && Style.isJava()) {
+ next();
+ continue;
+ }
+ if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
+ return false;
+ const auto &Prev = *CurrentToken->Previous;
+ // If a && or || is found and interpreted as a binary operator, this set
+ // of angles is likely part of something like "a < b && c > d". If the
+ // angles are inside an expression, the ||/&& might also be a binary
+ // operator that was misinterpreted because we are parsing template
+ // parameters.
+ // FIXME: This is getting out of hand, write a decent parser.
+ if (MaybeAngles && InExpr && !Line.startsWith(tok::kw_template) &&
+ Prev.is(TT_BinaryOperator) &&
+ Prev.isOneOf(tok::pipepipe, tok::ampamp)) {
+ MaybeAngles = false;
+ }
+ if (Prev.isOneOf(tok::question, tok::colon) && !Style.isProto())
+ SeenTernaryOperator = true;
+ updateParameterCount(Left, CurrentToken);
+ if (Style.Language == FormatStyle::LK_Proto) {
+ if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
+ if (CurrentToken->is(tok::colon) ||
+ (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
+ Previous->isNot(tok::colon))) {
+ Previous->setType(TT_SelectorName);
+ }
+ }
+ } else if (Style.isTableGen()) {
+ if (CurrentToken->isOneOf(tok::comma, tok::equal)) {
+ // They appear as separators. Unless they are not in class definition.
+ next();
+ continue;
+ }
+ // In angle, there must be Value like tokens. Types are also able to be
+ // parsed in the same way with Values.
+ if (!parseTableGenValue())
+ return false;
+ continue;
+ }
+ if (!consumeToken())
+ return false;
+ }
+ return false;
+ }
+
+ bool parseUntouchableParens() {
+ while (CurrentToken) {
+ CurrentToken->Finalized = true;
+ switch (CurrentToken->Tok.getKind()) {
+ case tok::l_paren:
+ next();
+ if (!parseUntouchableParens())
+ return false;
+ continue;
+ case tok::r_paren:
+ next();
+ return true;
+ default:
+ // no-op
+ break;
+ }
+ next();
+ }
+ return false;
+ }
+
+ bool parseParens(bool IsIf = false) {
+ if (!CurrentToken)
+ return false;
+ assert(CurrentToken->Previous && "Unknown previous token");
+ FormatToken &OpeningParen = *CurrentToken->Previous;
+ assert(OpeningParen.is(tok::l_paren));
+ FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
+ OpeningParen.ParentBracket = Contexts.back().ContextKind;
+ ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
+
+ // FIXME: This is a bit of a hack. Do better.
+ Contexts.back().ColonIsForRangeExpr =
+ Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
+
+ if (OpeningParen.Previous &&
+ OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
+ OpeningParen.Finalized = true;
+ return parseUntouchableParens();
+ }
+
+ bool StartsObjCSelector = false;
+ if (!Style.isVerilog()) {
+ if (FormatToken *MaybeSel = OpeningParen.Previous) {
+ // @selector( starts a selector.
+ if (MaybeSel->is(tok::objc_selector) && MaybeSel->Previous &&
+ MaybeSel->Previous->is(tok::at)) {
+ StartsObjCSelector = true;
+ }
+ }
+ }
+
+ if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
+ // Find the previous kw_operator token.
+ FormatToken *Prev = &OpeningParen;
+ while (Prev->isNot(tok::kw_operator)) {
+ Prev = Prev->Previous;
+ assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
+ }
+
+ // If faced with "a.operator*(argument)" or "a->operator*(argument)",
+ // i.e. the operator is called as a member function,
+ // then the argument must be an expression.
+ bool OperatorCalledAsMemberFunction =
+ Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
+ Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
+ } else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
+ Contexts.back().IsExpression = true;
+ Contexts.back().ContextType = Context::VerilogInstancePortList;
+ } else if (Style.isJavaScript() &&
+ (Line.startsWith(Keywords.kw_type, tok::identifier) ||
+ Line.startsWith(tok::kw_export, Keywords.kw_type,
+ tok::identifier))) {
+ // type X = (...);
+ // export type X = (...);
+ Contexts.back().IsExpression = false;
+ } else if (OpeningParen.Previous &&
+ (OpeningParen.Previous->isOneOf(
+ tok::kw_noexcept, tok::kw_explicit, tok::kw_while,
+ tok::l_paren, tok::comma, TT_CastRParen,
+ TT_BinaryOperator) ||
+ OpeningParen.Previous->isIf())) {
+ // if and while usually contain expressions.
+ Contexts.back().IsExpression = true;
+ } else if (Style.isJavaScript() && OpeningParen.Previous &&
+ (OpeningParen.Previous->is(Keywords.kw_function) ||
+ (OpeningParen.Previous->endsSequence(tok::identifier,
+ Keywords.kw_function)))) {
+ // function(...) or function f(...)
+ Contexts.back().IsExpression = false;
+ } else if (Style.isJavaScript() && OpeningParen.Previous &&
+ OpeningParen.Previous->is(TT_JsTypeColon)) {
+ // let x: (SomeType);
+ Contexts.back().IsExpression = false;
+ } else if (isLambdaParameterList(&OpeningParen)) {
+ // This is a parameter list of a lambda expression.
+ OpeningParen.setType(TT_LambdaDefinitionLParen);
+ Contexts.back().IsExpression = false;
+ } else if (OpeningParen.is(TT_RequiresExpressionLParen)) {
+ Contexts.back().IsExpression = false;
+ } else if (OpeningParen.Previous &&
+ OpeningParen.Previous->is(tok::kw__Generic)) {
+ Contexts.back().ContextType = Context::C11GenericSelection;
+ Contexts.back().IsExpression = true;
+ } else if (OpeningParen.Previous &&
+ OpeningParen.Previous->TokenText == "Q_PROPERTY") {
+ Contexts.back().ContextType = Context::QtProperty;
+ Contexts.back().IsExpression = false;
+ } else if (Line.InPPDirective &&
+ (!OpeningParen.Previous ||
+ OpeningParen.Previous->isNot(tok::identifier))) {
+ Contexts.back().IsExpression = true;
+ } else if (Contexts[Contexts.size() - 2].CaretFound) {
+ // This is the parameter list of an ObjC block.
+ Contexts.back().IsExpression = false;
+ } else if (OpeningParen.Previous &&
+ OpeningParen.Previous->is(TT_ForEachMacro)) {
+ // The first argument to a foreach macro is a declaration.
+ Contexts.back().ContextType = Context::ForEachMacro;
+ Contexts.back().IsExpression = false;
+ } else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen &&
+ OpeningParen.Previous->MatchingParen->isOneOf(
+ TT_ObjCBlockLParen, TT_FunctionTypeLParen)) {
+ Contexts.back().IsExpression = false;
+ } else if (!Line.MustBeDeclaration &&
+ (!Line.InPPDirective || (Line.InMacroBody && !Scopes.empty()))) {
+ bool IsForOrCatch =
+ OpeningParen.Previous &&
+ OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch);
+ Contexts.back().IsExpression = !IsForOrCatch;
+ }
+
+ if (Style.isTableGen()) {
+ if (FormatToken *Prev = OpeningParen.Previous) {
+ if (Prev->is(TT_TableGenCondOperator)) {
+ Contexts.back().IsTableGenCondOpe = true;
+ Contexts.back().IsExpression = true;
+ } else if (Contexts.size() > 1 &&
+ Contexts[Contexts.size() - 2].IsTableGenBangOpe) {
+ // Hack to handle bang operators. The parent context's flag
+ // was set by parseTableGenSimpleValue().
+ // We have to specify the context outside because the prev of "(" may
+ // be ">", not the bang operator in this case.
+ Contexts.back().IsTableGenBangOpe = true;
+ Contexts.back().IsExpression = true;
+ } else {
+ // Otherwise, this paren seems DAGArg.
+ if (!parseTableGenDAGArg())
+ return false;
+ return parseTableGenDAGArgAndList(&OpeningParen);
+ }
+ }
+ }
+
+ // Infer the role of the l_paren based on the previous token if we haven't
+ // detected one yet.
+ if (PrevNonComment && OpeningParen.is(TT_Unknown)) {
+ if (PrevNonComment->isAttribute()) {
+ OpeningParen.setType(TT_AttributeLParen);
+ } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
+ tok::kw_typeof,
+#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
+#include "clang/Basic/TransformTypeTraits.def"
+ tok::kw__Atomic)) {
+ OpeningParen.setType(TT_TypeDeclarationParen);
+ // decltype() and typeof() usually contain expressions.
+ if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
+ Contexts.back().IsExpression = true;
+ }
+ }
+
+ if (StartsObjCSelector)
+ OpeningParen.setType(TT_ObjCSelector);
+
+ const bool IsStaticAssert =
+ PrevNonComment && PrevNonComment->is(tok::kw_static_assert);
+ if (IsStaticAssert)
+ Contexts.back().InStaticAssertFirstArgument = true;
+
+ // MightBeFunctionType and ProbablyFunctionType are used for
+ // function pointer and reference types as well as Objective-C
+ // block types:
+ //
+ // void (*FunctionPointer)(void);
+ // void (&FunctionReference)(void);
+ // void (&&FunctionReference)(void);
+ // void (^ObjCBlock)(void);
+ bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
+ bool ProbablyFunctionType =
+ CurrentToken->isPointerOrReference() || CurrentToken->is(tok::caret);
+ bool HasMultipleLines = false;
+ bool HasMultipleParametersOnALine = false;
+ bool MightBeObjCForRangeLoop =
+ OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for);
+ FormatToken *PossibleObjCForInToken = nullptr;
+ while (CurrentToken) {
+ const auto &Prev = *CurrentToken->Previous;
+ const auto *PrevPrev = Prev.Previous;
+ if (Prev.is(TT_PointerOrReference) &&
+ PrevPrev->isOneOf(tok::l_paren, tok::coloncolon)) {
+ ProbablyFunctionType = true;
+ }
+ if (CurrentToken->is(tok::comma))
+ MightBeFunctionType = false;
+ if (Prev.is(TT_BinaryOperator))
+ Contexts.back().IsExpression = true;
+ if (CurrentToken->is(tok::r_paren)) {
+ if (Prev.is(TT_PointerOrReference) &&
+ (PrevPrev == &OpeningParen || PrevPrev->is(tok::coloncolon))) {
+ MightBeFunctionType = true;
+ }
+ if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType &&
+ ProbablyFunctionType && CurrentToken->Next &&
+ (CurrentToken->Next->is(tok::l_paren) ||
+ (CurrentToken->Next->is(tok::l_square) &&
+ (Line.MustBeDeclaration ||
+ (PrevNonComment && PrevNonComment->isTypeName(LangOpts)))))) {
+ OpeningParen.setType(OpeningParen.Next->is(tok::caret)
+ ? TT_ObjCBlockLParen
+ : TT_FunctionTypeLParen);
+ }
+ OpeningParen.MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = &OpeningParen;
+
+ if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
+ OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) {
+ // Detect the case where macros are used to generate lambdas or
+ // function bodies, e.g.:
+ // auto my_lambda = MACRO((Type *type, int i) { .. body .. });
+ for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
+ Tok = Tok->Next) {
+ if (Tok->is(TT_BinaryOperator) && Tok->isPointerOrReference())
+ Tok->setType(TT_PointerOrReference);
+ }
+ }
+
+ if (StartsObjCSelector) {
+ CurrentToken->setType(TT_ObjCSelector);
+ if (Contexts.back().FirstObjCSelectorName) {
+ Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
+ Contexts.back().LongestObjCSelectorName;
+ }
+ }
+
+ if (OpeningParen.is(TT_AttributeLParen))
+ CurrentToken->setType(TT_AttributeRParen);
+ if (OpeningParen.is(TT_TypeDeclarationParen))
+ CurrentToken->setType(TT_TypeDeclarationParen);
+ if (OpeningParen.Previous &&
+ OpeningParen.Previous->is(TT_JavaAnnotation)) {
+ CurrentToken->setType(TT_JavaAnnotation);
+ }
+ if (OpeningParen.Previous &&
+ OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) {
+ CurrentToken->setType(TT_LeadingJavaAnnotation);
+ }
+
+ if (!HasMultipleLines)
+ OpeningParen.setPackingKind(PPK_Inconclusive);
+ else if (HasMultipleParametersOnALine)
+ OpeningParen.setPackingKind(PPK_BinPacked);
+ else
+ OpeningParen.setPackingKind(PPK_OnePerLine);
+
+ next();
+ return true;
+ }
+ if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
+ return false;
+
+ if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen))
+ OpeningParen.setType(TT_Unknown);
+ if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
+ !CurrentToken->Next->HasUnescapedNewline &&
+ !CurrentToken->Next->isTrailingComment()) {
+ HasMultipleParametersOnALine = true;
+ }
+ bool ProbablyFunctionTypeLParen =
+ (CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
+ CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
+ if ((Prev.isOneOf(tok::kw_const, tok::kw_auto) ||
+ Prev.isTypeName(LangOpts)) &&
+ !(CurrentToken->is(tok::l_brace) ||
+ (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) {
+ Contexts.back().IsExpression = false;
+ }
+ if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
+ MightBeObjCForRangeLoop = false;
+ if (PossibleObjCForInToken) {
+ PossibleObjCForInToken->setType(TT_Unknown);
+ PossibleObjCForInToken = nullptr;
+ }
+ }
+ if (IsIf && CurrentToken->is(tok::semi)) {
+ for (auto *Tok = OpeningParen.Next;
+ Tok != CurrentToken &&
+ Tok->isNoneOf(tok::equal, tok::l_paren, tok::l_brace);
+ Tok = Tok->Next) {
+ if (Tok->isPointerOrReference())
+ Tok->setFinalizedType(TT_PointerOrReference);
+ }
+ }
+ if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
+ PossibleObjCForInToken = CurrentToken;
+ PossibleObjCForInToken->setType(TT_ObjCForIn);
+ }
+ // When we discover a 'new', we set CanBeExpression to 'false' in order to
+ // parse the type correctly. Reset that after a comma.
+ if (CurrentToken->is(tok::comma)) {
+ if (IsStaticAssert)
+ Contexts.back().InStaticAssertFirstArgument = false;
+ else
+ Contexts.back().CanBeExpression = true;
+ }
+
+ if (Style.isTableGen()) {
+ if (CurrentToken->is(tok::comma)) {
+ if (Contexts.back().IsTableGenCondOpe)
+ CurrentToken->setType(TT_TableGenCondOperatorComma);
+ next();
+ } else if (CurrentToken->is(tok::colon)) {
+ if (Contexts.back().IsTableGenCondOpe)
+ CurrentToken->setType(TT_TableGenCondOperatorColon);
+ next();
+ }
+ // In TableGen there must be Values in parens.
+ if (!parseTableGenValue())
+ return false;
+ continue;
+ }
+
+ FormatToken *Tok = CurrentToken;
+ if (!consumeToken())
+ return false;
+ updateParameterCount(&OpeningParen, Tok);
+ if (CurrentToken && CurrentToken->HasUnescapedNewline)
+ HasMultipleLines = true;
+ }
+ return false;
+ }
+
+ bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
+ if (!Style.isCSharp())
+ return false;
+
+ // `identifier[i]` is not an attribute.
+ if (Tok.Previous && Tok.Previous->is(tok::identifier))
+ return false;
+
+ // Chains of [] in `identifier[i][j][k]` are not attributes.
+ if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
+ auto *MatchingParen = Tok.Previous->MatchingParen;
+ if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
+ return false;
+ }
+
+ const FormatToken *AttrTok = Tok.Next;
+ if (!AttrTok)
+ return false;
+
+ // Just an empty declaration e.g. string [].
+ if (AttrTok->is(tok::r_square))
+ return false;
+
+ // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
+ while (AttrTok && AttrTok->isNot(tok::r_square))
+ AttrTok = AttrTok->Next;
+
+ if (!AttrTok)
+ return false;
+
+ // Allow an attribute to be the only content of a file.
+ AttrTok = AttrTok->Next;
+ if (!AttrTok)
+ return true;
+
+ // Limit this to being an access modifier that follows.
+ if (AttrTok->isAccessSpecifierKeyword() ||
+ AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
+ tok::l_square, Keywords.kw_internal)) {
+ return true;
+ }
+
+ // incase its a [XXX] retval func(....
+ if (AttrTok->Next &&
+ AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ bool parseSquare() {
+ if (!CurrentToken)
+ return false;
+
+ // A '[' could be an index subscript (after an identifier or after
+ // ')' or ']'), it could be the start of an Objective-C method
+ // expression, it could the start of an Objective-C array literal,
+ // or it could be a C++ attribute specifier [[foo::bar]].
+ FormatToken *Left = CurrentToken->Previous;
+ Left->ParentBracket = Contexts.back().ContextKind;
+ FormatToken *Parent = Left->getPreviousNonComment();
+
+ // Cases where '>' is followed by '['.
+ // In C++, this can happen either in array of templates (foo<int>[10])
+ // or when array is a nested template type (unique_ptr<type1<type2>[]>).
+ bool CppArrayTemplates =
+ IsCpp && Parent && Parent->is(TT_TemplateCloser) &&
+ (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
+ Contexts.back().ContextType == Context::TemplateArgument);
+
+ const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
+ const bool IsCpp11AttributeSpecifier =
+ isCppAttribute(IsCpp, *Left) || IsInnerSquare;
+
+ // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
+ bool IsCSharpAttributeSpecifier =
+ isCSharpAttributeSpecifier(*Left) ||
+ Contexts.back().InCSharpAttributeSpecifier;
+
+ bool InsideInlineASM = Line.startsWith(tok::kw_asm);
+ bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
+ bool StartsObjCMethodExpr =
+ !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
+ IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
+ Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
+ CurrentToken->isNoneOf(tok::l_brace, tok::r_square) &&
+ // Do not consider '[' after a comma inside a braced initializer the
+ // start of an ObjC method expression. In braced initializer lists,
+ // commas are list separators and should not trigger ObjC parsing.
+ (!Parent || !Parent->is(tok::comma) ||
+ Contexts.back().ContextKind != tok::l_brace) &&
+ (!Parent ||
+ Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
+ tok::kw_return, tok::kw_throw) ||
+ Parent->isUnaryOperator() ||
+ // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
+ Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
+ (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
+ prec::Unknown));
+ bool ColonFound = false;
+
+ unsigned BindingIncrease = 1;
+ if (IsCppStructuredBinding) {
+ Left->setType(TT_StructuredBindingLSquare);
+ } else if (Left->is(TT_Unknown)) {
+ if (StartsObjCMethodExpr) {
+ Left->setType(TT_ObjCMethodExpr);
+ } else if (InsideInlineASM) {
+ Left->setType(TT_InlineASMSymbolicNameLSquare);
+ } else if (IsCpp11AttributeSpecifier) {
+ if (!IsInnerSquare) {
+ Left->setType(TT_AttributeLSquare);
+ if (Left->Previous)
+ Left->Previous->EndsCppAttributeGroup = false;
+ }
+ } else if (Style.isJavaScript() && Parent &&
+ Contexts.back().ContextKind == tok::l_brace &&
+ Parent->isOneOf(tok::l_brace, tok::comma)) {
+ Left->setType(TT_JsComputedPropertyName);
+ } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
+ Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
+ Left->setType(TT_DesignatedInitializerLSquare);
+ } else if (IsCSharpAttributeSpecifier) {
+ Left->setType(TT_AttributeLSquare);
+ } else if (CurrentToken->is(tok::r_square) && Parent &&
+ Parent->is(TT_TemplateCloser)) {
+ Left->setType(TT_ArraySubscriptLSquare);
+ } else if (Style.isProto()) {
+ // Square braces in LK_Proto can either be message field attributes:
+ //
+ // optional Aaa aaa = 1 [
+ // (aaa) = aaa
+ // ];
+ //
+ // extensions 123 [
+ // (aaa) = aaa
+ // ];
+ //
+ // or text proto extensions (in options):
+ //
+ // option (Aaa.options) = {
+ // [type.type/type] {
+ // key: value
+ // }
+ // }
+ //
+ // or repeated fields (in options):
+ //
+ // option (Aaa.options) = {
+ // keys: [ 1, 2, 3 ]
+ // }
+ //
+ // In the first and the third case we want to spread the contents inside
+ // the square braces; in the second we want to keep them inline.
+ Left->setType(TT_ArrayInitializerLSquare);
+ if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
+ tok::equal) &&
+ !Left->endsSequence(tok::l_square, tok::numeric_constant,
+ tok::identifier) &&
+ !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
+ Left->setType(TT_ProtoExtensionLSquare);
+ BindingIncrease = 10;
+ }
+ } else if (!CppArrayTemplates && Parent &&
+ Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
+ tok::comma, tok::l_paren, tok::l_square,
+ tok::question, tok::colon, tok::kw_return,
+ // Should only be relevant to JavaScript:
+ tok::kw_default)) {
+ Left->setType(TT_ArrayInitializerLSquare);
+ } else {
+ BindingIncrease = 10;
+ Left->setType(TT_ArraySubscriptLSquare);
+ }
+ }
+
+ ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
+ Contexts.back().IsExpression = true;
+ if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon))
+ Contexts.back().IsExpression = false;
+
+ Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
+ Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
+ Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
+
+ while (CurrentToken) {
+ if (CurrentToken->is(tok::r_square)) {
+ if (IsCpp11AttributeSpecifier && !IsInnerSquare) {
+ CurrentToken->setType(TT_AttributeRSquare);
+ CurrentToken->EndsCppAttributeGroup = true;
+ }
+ if (IsCSharpAttributeSpecifier) {
+ CurrentToken->setType(TT_AttributeRSquare);
+ } else if (((CurrentToken->Next &&
+ CurrentToken->Next->is(tok::l_paren)) ||
+ (CurrentToken->Previous &&
+ CurrentToken->Previous->Previous == Left)) &&
+ Left->is(TT_ObjCMethodExpr)) {
+ // An ObjC method call is rarely followed by an open parenthesis. It
+ // also can't be composed of just one token, unless it's a macro that
+ // will be expanded to more tokens.
+ // FIXME: Do we incorrectly label ":" with this?
+ StartsObjCMethodExpr = false;
+ Left->setType(TT_Unknown);
+ }
+ if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
+ CurrentToken->setType(TT_ObjCMethodExpr);
+ // If we haven't seen a colon yet, make sure the last identifier
+ // before the r_square is tagged as a selector name component.
+ if (!ColonFound && CurrentToken->Previous &&
+ CurrentToken->Previous->is(TT_Unknown) &&
+ canBeObjCSelectorComponent(*CurrentToken->Previous)) {
+ CurrentToken->Previous->setType(TT_SelectorName);
+ }
+ // determineStarAmpUsage() thinks that '*' '[' is allocating an
+ // array of pointers, but if '[' starts a selector then '*' is a
+ // binary operator.
+ if (Parent && Parent->is(TT_PointerOrReference))
+ Parent->overwriteFixedType(TT_BinaryOperator);
+ }
+ Left->MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = Left;
+ // FirstObjCSelectorName is set when a colon is found. This does
+ // not work, however, when the method has no parameters.
+ // Here, we set FirstObjCSelectorName when the end of the method call is
+ // reached, in case it was not set already.
+ if (!Contexts.back().FirstObjCSelectorName) {
+ FormatToken *Previous = CurrentToken->getPreviousNonComment();
+ if (Previous && Previous->is(TT_SelectorName)) {
+ Previous->ObjCSelectorNameParts = 1;
+ Contexts.back().FirstObjCSelectorName = Previous;
+ }
+ } else {
+ Left->ParameterCount =
+ Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
+ }
+ if (Contexts.back().FirstObjCSelectorName) {
+ Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
+ Contexts.back().LongestObjCSelectorName;
+ if (Left->BlockParameterCount > 1)
+ Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
+ }
+ if (Style.isTableGen() && Left->is(TT_TableGenListOpener))
+ CurrentToken->setType(TT_TableGenListCloser);
+ next();
+ return true;
+ }
+ if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
+ return false;
+ if (CurrentToken->is(tok::colon)) {
+ if (IsCpp11AttributeSpecifier &&
+ CurrentToken->endsSequence(tok::colon, tok::identifier,
+ tok::kw_using)) {
+ // Remember that this is a [[using ns: foo]] C++ attribute, so we
+ // don't add a space before the colon (unlike other colons).
+ CurrentToken->setType(TT_AttributeColon);
+ } else if (!Style.isVerilog() && !Line.InPragmaDirective &&
+ Left->isOneOf(TT_ArraySubscriptLSquare,
+ TT_DesignatedInitializerLSquare)) {
+ Left->setType(TT_ObjCMethodExpr);
+ StartsObjCMethodExpr = true;
+ Contexts.back().ColonIsObjCMethodExpr = true;
+ if (Parent && Parent->is(tok::r_paren)) {
+ // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
+ Parent->setType(TT_CastRParen);
+ }
+ }
+ ColonFound = true;
+ }
+ if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
+ !ColonFound) {
+ Left->setType(TT_ArrayInitializerLSquare);
+ }
+ FormatToken *Tok = CurrentToken;
+ if (Style.isTableGen()) {
+ if (CurrentToken->isOneOf(tok::comma, tok::minus, tok::ellipsis)) {
+ // '-' and '...' appears as a separator in slice.
+ next();
+ } else {
+ // In TableGen there must be a list of Values in square brackets.
+ // It must be ValueList or SliceElements.
+ if (!parseTableGenValue())
+ return false;
+ }
+ updateParameterCount(Left, Tok);
+ continue;
+ }
+ if (!consumeToken())
+ return false;
+ updateParameterCount(Left, Tok);
+ }
+ return false;
+ }
+
+ void skipToNextNonComment() {
+ next();
+ while (CurrentToken && CurrentToken->is(tok::comment))
+ next();
+ }
+
+ // Simplified parser for TableGen Value. Returns true on success.
+ // It consists of SimpleValues, SimpleValues with Suffixes, and Value followed
+ // by '#', paste operator.
+ // There also exists the case the Value is parsed as NameValue.
+ // In this case, the Value ends if '{' is found.
+ bool parseTableGenValue(bool ParseNameMode = false) {
+ if (!CurrentToken)
+ return false;
+ while (CurrentToken->is(tok::comment))
+ next();
+ if (!parseTableGenSimpleValue())
+ return false;
+ if (!CurrentToken)
+ return true;
+ // Value "#" [Value]
+ if (CurrentToken->is(tok::hash)) {
+ if (CurrentToken->Next &&
+ CurrentToken->Next->isOneOf(tok::colon, tok::semi, tok::l_brace)) {
+ // Trailing paste operator.
+ // These are only the allowed cases in TGParser::ParseValue().
+ CurrentToken->setType(TT_TableGenTrailingPasteOperator);
+ next();
+ return true;
+ }
+ FormatToken *HashTok = CurrentToken;
+ skipToNextNonComment();
+ HashTok->setType(TT_Unknown);
+ if (!parseTableGenValue(ParseNameMode))
+ return false;
+ if (!CurrentToken)
+ return true;
+ }
+ // In name mode, '{' is regarded as the end of the value.
+ // See TGParser::ParseValue in TGParser.cpp
+ if (ParseNameMode && CurrentToken->is(tok::l_brace))
+ return true;
+ // These tokens indicates this is a value with suffixes.
+ if (CurrentToken->isOneOf(tok::l_brace, tok::l_square, tok::period)) {
+ CurrentToken->setType(TT_TableGenValueSuffix);
+ FormatToken *Suffix = CurrentToken;
+ skipToNextNonComment();
+ if (Suffix->is(tok::l_square))
+ return parseSquare();
+ if (Suffix->is(tok::l_brace)) {
+ Scopes.push_back(getScopeType(*Suffix));
+ return parseBrace();
+ }
+ }
+ return true;
+ }
+
+ // TokVarName ::= "$" ualpha (ualpha | "0"..."9")*
+ // Appears as a part of DagArg.
+ // This does not change the current token on fail.
+ bool tryToParseTableGenTokVar() {
+ if (!CurrentToken)
+ return false;
+ if (CurrentToken->is(tok::identifier) &&
+ CurrentToken->TokenText.front() == '$') {
+ skipToNextNonComment();
+ return true;
+ }
+ return false;
+ }
+
+ // DagArg ::= Value [":" TokVarName] | TokVarName
+ // Appears as a part of SimpleValue6.
+ bool parseTableGenDAGArg(bool AlignColon = false) {
+ if (tryToParseTableGenTokVar())
+ return true;
+ if (parseTableGenValue()) {
+ if (CurrentToken && CurrentToken->is(tok::colon)) {
+ if (AlignColon)
+ CurrentToken->setType(TT_TableGenDAGArgListColonToAlign);
+ else
+ CurrentToken->setType(TT_TableGenDAGArgListColon);
+ skipToNextNonComment();
+ return tryToParseTableGenTokVar();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ // Judge if the token is a operator ID to insert line break in DAGArg.
+ // That is, TableGenBreakingDAGArgOperators is empty (by the definition of the
+ // option) or the token is in the list.
+ bool isTableGenDAGArgBreakingOperator(const FormatToken &Tok) {
+ auto &Opes = Style.TableGenBreakingDAGArgOperators;
+ // If the list is empty, all operators are breaking operators.
+ if (Opes.empty())
+ return true;
+ // Otherwise, the operator is limited to normal identifiers.
+ if (Tok.isNot(tok::identifier) ||
+ Tok.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator)) {
+ return false;
+ }
+ // The case next is colon, it is not a operator of identifier.
+ if (!Tok.Next || Tok.Next->is(tok::colon))
+ return false;
+ return llvm::is_contained(Opes, Tok.TokenText.str());
+ }
+
+ // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
+ // This parses SimpleValue 6's inside part of "(" ")"
+ bool parseTableGenDAGArgAndList(FormatToken *Opener) {
+ FormatToken *FirstTok = CurrentToken;
+ if (!parseTableGenDAGArg())
+ return false;
+ bool BreakInside = false;
+ if (Style.TableGenBreakInsideDAGArg != FormatStyle::DAS_DontBreak) {
+ // Specialized detection for DAGArgOperator, that determines the way of
+ // line break for this DAGArg elements.
+ if (isTableGenDAGArgBreakingOperator(*FirstTok)) {
+ // Special case for identifier DAGArg operator.
+ BreakInside = true;
+ Opener->setType(TT_TableGenDAGArgOpenerToBreak);
+ if (FirstTok->isOneOf(TT_TableGenBangOperator,
+ TT_TableGenCondOperator)) {
+ // Special case for bang/cond operators. Set the whole operator as
+ // the DAGArg operator. Always break after it.
+ CurrentToken->Previous->setType(TT_TableGenDAGArgOperatorToBreak);
+ } else if (FirstTok->is(tok::identifier)) {
+ if (Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll)
+ FirstTok->setType(TT_TableGenDAGArgOperatorToBreak);
+ else
+ FirstTok->setType(TT_TableGenDAGArgOperatorID);
+ }
+ }
+ }
+ // Parse the [DagArgList] part
+ return parseTableGenDAGArgList(Opener, BreakInside);
+ }
+
+ // DagArgList ::= "," DagArg [DagArgList]
+ // This parses SimpleValue 6's [DagArgList] part.
+ bool parseTableGenDAGArgList(FormatToken *Opener, bool BreakInside) {
+ ScopedContextCreator ContextCreator(*this, tok::l_paren, 0);
+ Contexts.back().IsTableGenDAGArgList = true;
+ bool FirstDAGArgListElm = true;
+ while (CurrentToken) {
+ if (!FirstDAGArgListElm && CurrentToken->is(tok::comma)) {
+ CurrentToken->setType(BreakInside ? TT_TableGenDAGArgListCommaToBreak
+ : TT_TableGenDAGArgListComma);
+ skipToNextNonComment();
+ }
+ if (CurrentToken && CurrentToken->is(tok::r_paren)) {
+ CurrentToken->setType(TT_TableGenDAGArgCloser);
+ Opener->MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = Opener;
+ skipToNextNonComment();
+ return true;
+ }
+ if (!parseTableGenDAGArg(
+ BreakInside &&
+ Style.AlignConsecutiveTableGenBreakingDAGArgColons.Enabled)) {
+ return false;
+ }
+ FirstDAGArgListElm = false;
+ }
+ return false;
+ }
+
+ bool parseTableGenSimpleValue() {
+ assert(Style.isTableGen());
+ if (!CurrentToken)
+ return false;
+ FormatToken *Tok = CurrentToken;
+ skipToNextNonComment();
+ // SimpleValue 1, 2, 3: Literals
+ if (Tok->isOneOf(tok::numeric_constant, tok::string_literal,
+ TT_TableGenMultiLineString, tok::kw_true, tok::kw_false,
+ tok::question, tok::kw_int)) {
+ return true;
+ }
+ // SimpleValue 4: ValueList, Type
+ if (Tok->is(tok::l_brace)) {
+ Scopes.push_back(getScopeType(*Tok));
+ return parseBrace();
+ }
+ // SimpleValue 5: List initializer
+ if (Tok->is(tok::l_square)) {
+ Tok->setType(TT_TableGenListOpener);
+ if (!parseSquare())
+ return false;
+ if (Tok->is(tok::less)) {
+ CurrentToken->setType(TT_TemplateOpener);
+ return parseAngle();
+ }
+ return true;
+ }
+ // SimpleValue 6: DAGArg [DAGArgList]
+ // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
+ if (Tok->is(tok::l_paren)) {
+ Tok->setType(TT_TableGenDAGArgOpener);
+ // Nested DAGArg requires space before '(' as separator.
+ if (Contexts.back().IsTableGenDAGArgList)
+ Tok->SpacesRequiredBefore = 1;
+ return parseTableGenDAGArgAndList(Tok);
+ }
+ // SimpleValue 9: Bang operator
+ if (Tok->is(TT_TableGenBangOperator)) {
+ if (CurrentToken && CurrentToken->is(tok::less)) {
+ CurrentToken->setType(TT_TemplateOpener);
+ skipToNextNonComment();
+ if (!parseAngle())
+ return false;
+ }
+ if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
+ return false;
+ next();
+ // FIXME: Hack using inheritance to child context
+ Contexts.back().IsTableGenBangOpe = true;
+ bool Result = parseParens();
+ Contexts.back().IsTableGenBangOpe = false;
+ return Result;
+ }
+ // SimpleValue 9: Cond operator
+ if (Tok->is(TT_TableGenCondOperator)) {
+ if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
+ return false;
+ next();
+ return parseParens();
+ }
+ // We have to check identifier at the last because the kind of bang/cond
+ // operators are also identifier.
+ // SimpleValue 7: Identifiers
+ if (Tok->is(tok::identifier)) {
+ // SimpleValue 8: Anonymous record
+ if (CurrentToken && CurrentToken->is(tok::less)) {
+ CurrentToken->setType(TT_TemplateOpener);
+ skipToNextNonComment();
+ return parseAngle();
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ bool couldBeInStructArrayInitializer() const {
+ if (Contexts.size() < 2)
+ return false;
+ // We want to back up no more then 2 context levels i.e.
+ // . { { <-
+ const auto End = std::next(Contexts.rbegin(), 2);
+ auto Last = Contexts.rbegin();
+ unsigned Depth = 0;
+ for (; Last != End; ++Last)
+ if (Last->ContextKind == tok::l_brace)
+ ++Depth;
+ return Depth == 2 && Last->ContextKind != tok::l_brace;
+ }
+
+ bool parseBrace() {
+ if (!CurrentToken)
+ return true;
+
+ assert(CurrentToken->Previous);
+ FormatToken &OpeningBrace = *CurrentToken->Previous;
+ assert(OpeningBrace.is(tok::l_brace));
+ OpeningBrace.ParentBracket = Contexts.back().ContextKind;
+
+ if (Contexts.back().CaretFound)
+ OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace);
+ Contexts.back().CaretFound = false;
+
+ ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
+ Contexts.back().ColonIsDictLiteral = true;
+ if (OpeningBrace.is(BK_BracedInit))
+ Contexts.back().IsExpression = true;
+ if (Style.isJavaScript() && OpeningBrace.Previous &&
+ OpeningBrace.Previous->is(TT_JsTypeColon)) {
+ Contexts.back().IsExpression = false;
+ }
+ if (Style.isVerilog() &&
+ (!OpeningBrace.getPreviousNonComment() ||
+ OpeningBrace.getPreviousNonComment()->isNot(Keywords.kw_apostrophe))) {
+ Contexts.back().VerilogMayBeConcatenation = true;
+ }
+ if (Style.isTableGen())
+ Contexts.back().ColonIsDictLiteral = false;
+
+ unsigned CommaCount = 0;
+ while (CurrentToken) {
+ if (CurrentToken->is(tok::r_brace)) {
+ assert(!Scopes.empty());
+ assert(Scopes.back() == getScopeType(OpeningBrace));
+ Scopes.pop_back();
+ assert(OpeningBrace.Optional == CurrentToken->Optional);
+ OpeningBrace.MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = &OpeningBrace;
+ if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
+ if (OpeningBrace.ParentBracket == tok::l_brace &&
+ couldBeInStructArrayInitializer() && CommaCount > 0) {
+ Contexts.back().ContextType = Context::StructArrayInitializer;
+ }
+ }
+ next();
+ return true;
+ }
+ if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
+ return false;
+ updateParameterCount(&OpeningBrace, CurrentToken);
+ if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
+ FormatToken *Previous = CurrentToken->getPreviousNonComment();
+ if (Previous->is(TT_JsTypeOptionalQuestion))
+ Previous = Previous->getPreviousNonComment();
+ if ((CurrentToken->is(tok::colon) && !Style.isTableGen() &&
+ (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
+ Style.isProto()) {
+ OpeningBrace.setType(TT_DictLiteral);
+ if (Previous->Tok.getIdentifierInfo() ||
+ Previous->is(tok::string_literal)) {
+ Previous->setType(TT_SelectorName);
+ }
+ }
+ if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown) &&
+ !Style.isTableGen()) {
+ OpeningBrace.setType(TT_DictLiteral);
+ } else if (Style.isJavaScript()) {
+ OpeningBrace.overwriteFixedType(TT_DictLiteral);
+ }
+ }
+ bool IsBracedListComma = false;
+ if (CurrentToken->is(tok::comma)) {
+ if (Style.isJavaScript())
+ OpeningBrace.overwriteFixedType(TT_DictLiteral);
+ else
+ IsBracedListComma = OpeningBrace.is(BK_BracedInit);
+ ++CommaCount;
+ }
+ if (!consumeToken())
+ return false;
+ if (IsBracedListComma)
+ Contexts.back().IsExpression = true;
+ }
+ return true;
+ }
+
+ void updateParameterCount(FormatToken *Left, FormatToken *Current) {
+ // For ObjC methods, the number of parameters is calculated differently as
+ // method declarations have a different structure (the parameters are not
+ // inside a bracket scope).
+ if (Current->is(tok::l_brace) && Current->is(BK_Block))
+ ++Left->BlockParameterCount;
+ if (Current->is(tok::comma)) {
+ ++Left->ParameterCount;
+ if (!Left->Role)
+ Left->Role.reset(new CommaSeparatedList(Style));
+ Left->Role->CommaFound(Current);
+ } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
+ Left->ParameterCount = 1;
+ }
+ }
+
+ bool parseConditional() {
+ while (CurrentToken) {
+ if (CurrentToken->is(tok::colon) && CurrentToken->is(TT_Unknown)) {
+ CurrentToken->setType(TT_ConditionalExpr);
+ next();
+ return true;
+ }
+ if (!consumeToken())
+ return false;
+ }
+ return false;
+ }
+
+ bool parseTemplateDeclaration() {
+ if (!CurrentToken || CurrentToken->isNot(tok::less))
+ return false;
+
+ CurrentToken->setType(TT_TemplateOpener);
+ next();
+
+ TemplateDeclarationDepth++;
+ const bool WellFormed = parseAngle();
+ TemplateDeclarationDepth--;
+ if (!WellFormed)
+ return false;
+
+ if (CurrentToken && TemplateDeclarationDepth == 0)
+ CurrentToken->Previous->ClosesTemplateDeclaration = true;
+
+ return true;
+ }
+
+ bool consumeToken() {
+ if (IsCpp) {
+ const auto *Prev = CurrentToken->getPreviousNonComment();
+ if (Prev && Prev->is(TT_AttributeRSquare) &&
+ CurrentToken->isOneOf(tok::kw_if, tok::kw_switch, tok::kw_case,
+ tok::kw_default, tok::kw_for, tok::kw_while) &&
+ mustBreakAfterAttributes(*CurrentToken, Style)) {
+ CurrentToken->MustBreakBefore = true;
+ }
+ }
+ FormatToken *Tok = CurrentToken;
+ next();
+ // In Verilog primitives' state tables, `:`, `?`, and `-` aren't normal
+ // operators.
+ if (Tok->is(TT_VerilogTableItem))
+ return true;
+ // Multi-line string itself is a single annotated token.
+ if (Tok->is(TT_TableGenMultiLineString))
+ return true;
+ auto *Prev = Tok->getPreviousNonComment();
+ auto *Next = Tok->getNextNonComment();
+ switch (bool IsIf = false; Tok->Tok.getKind()) {
+ case tok::plus:
+ case tok::minus:
+ if (!Prev && Line.MustBeDeclaration)
+ Tok->setType(TT_ObjCMethodSpecifier);
+ break;
+ case tok::colon:
+ if (!Prev)
+ return false;
+ // Goto labels and case labels are already identified in
+ // UnwrappedLineParser.
+ if (Tok->isTypeFinalized())
+ break;
+ // Colons from ?: are handled in parseConditional().
+ if (Style.isJavaScript()) {
+ if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
+ (Contexts.size() == 1 && // switch/case labels
+ Line.First->isNoneOf(tok::kw_enum, tok::kw_case)) ||
+ Contexts.back().ContextKind == tok::l_paren || // function params
+ Contexts.back().ContextKind == tok::l_square || // array type
+ (!Contexts.back().IsExpression &&
+ Contexts.back().ContextKind == tok::l_brace) || // object type
+ (Contexts.size() == 1 &&
+ Line.MustBeDeclaration)) { // method/property declaration
+ Contexts.back().IsExpression = false;
+ Tok->setType(TT_JsTypeColon);
+ break;
+ }
+ } else if (Style.isCSharp()) {
+ if (Contexts.back().InCSharpAttributeSpecifier) {
+ Tok->setType(TT_AttributeColon);
+ break;
+ }
+ if (Contexts.back().ContextKind == tok::l_paren) {
+ Tok->setType(TT_CSharpNamedArgumentColon);
+ break;
+ }
+ } else if (Style.isVerilog() && Tok->isNot(TT_BinaryOperator)) {
+ // The distribution weight operators are labeled
+ // TT_BinaryOperator by the lexer.
+ if (Keywords.isVerilogEnd(*Prev) || Keywords.isVerilogBegin(*Prev)) {
+ Tok->setType(TT_VerilogBlockLabelColon);
+ } else if (Contexts.back().ContextKind == tok::l_square) {
+ Tok->setType(TT_BitFieldColon);
+ } else if (Contexts.back().ColonIsDictLiteral) {
+ Tok->setType(TT_DictLiteral);
+ } else if (Contexts.size() == 1) {
+ // In Verilog a case label doesn't have the case keyword. We
+ // assume a colon following an expression is a case label.
+ // Colons from ?: are annotated in parseConditional().
+ Tok->setType(TT_CaseLabelColon);
+ if (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))
+ --Line.Level;
+ }
+ break;
+ }
+ if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) ||
+ Line.First->startsSequence(tok::kw_export, Keywords.kw_module) ||
+ Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) {
+ Tok->setType(TT_ModulePartitionColon);
+ } else if (Line.First->is(tok::kw_asm)) {
+ Tok->setType(TT_InlineASMColon);
+ } else if (Contexts.back().ColonIsDictLiteral || Style.isProto()) {
+ Tok->setType(TT_DictLiteral);
+ if (Style.isTextProto())
+ Prev->setType(TT_SelectorName);
+ } else if (Contexts.back().ColonIsObjCMethodExpr ||
+ Line.startsWith(TT_ObjCMethodSpecifier)) {
+ Tok->setType(TT_ObjCMethodExpr);
+ const auto *PrevPrev = Prev->Previous;
+ // Ensure we tag all identifiers in method declarations as
+ // TT_SelectorName.
+ bool UnknownIdentifierInMethodDeclaration =
+ Line.startsWith(TT_ObjCMethodSpecifier) &&
+ Prev->is(tok::identifier) && Prev->is(TT_Unknown);
+ if (!PrevPrev ||
+ // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
+ !(PrevPrev->is(TT_CastRParen) ||
+ (PrevPrev->is(TT_ObjCMethodExpr) && PrevPrev->is(tok::colon))) ||
+ PrevPrev->is(tok::r_square) ||
+ Contexts.back().LongestObjCSelectorName == 0 ||
+ UnknownIdentifierInMethodDeclaration) {
+ Prev->setType(TT_SelectorName);
+ if (!Contexts.back().FirstObjCSelectorName)
+ Contexts.back().FirstObjCSelectorName = Prev;
+ else if (Prev->ColumnWidth > Contexts.back().LongestObjCSelectorName)
+ Contexts.back().LongestObjCSelectorName = Prev->ColumnWidth;
+ Prev->ParameterIndex =
+ Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
+ ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
+ }
+ } else if (Contexts.back().ColonIsForRangeExpr) {
+ Tok->setType(TT_RangeBasedForLoopColon);
+ for (auto *Token = Prev;
+ Token && Token->isNoneOf(tok::semi, tok::l_paren);
+ Token = Token->Previous) {
+ if (Token->isPointerOrReference())
+ Token->setFinalizedType(TT_PointerOrReference);
+ }
+ } else if (Contexts.back().ContextType == Context::C11GenericSelection) {
+ Tok->setType(TT_GenericSelectionColon);
+ if (Prev->isPointerOrReference())
+ Prev->setFinalizedType(TT_PointerOrReference);
+ } else if ((CurrentToken && CurrentToken->is(tok::numeric_constant)) ||
+ (Prev->is(TT_StartOfName) && !Scopes.empty() &&
+ Scopes.back() == ST_Class)) {
+ Tok->setType(TT_BitFieldColon);
+ } else if (Contexts.size() == 1 &&
+ Line.getFirstNonComment()->isNoneOf(tok::kw_enum, tok::kw_case,
+ tok::kw_default) &&
+ !Line.startsWith(tok::kw_typedef, tok::kw_enum)) {
+ if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept) ||
+ Prev->ClosesRequiresClause) {
+ Tok->setType(TT_CtorInitializerColon);
+ } else if (Prev->is(tok::kw_try)) {
+ // Member initializer list within function try block.
+ FormatToken *PrevPrev = Prev->getPreviousNonComment();
+ if (!PrevPrev)
+ break;
+ if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept))
+ Tok->setType(TT_CtorInitializerColon);
+ } else {
+ Tok->setType(TT_InheritanceColon);
+ if (Prev->isAccessSpecifierKeyword())
+ Line.Type = LT_AccessModifier;
+ }
+ } else if (canBeObjCSelectorComponent(*Prev) && Next &&
+ (Next->isOneOf(tok::r_paren, tok::comma) ||
+ (canBeObjCSelectorComponent(*Next) && Next->Next &&
+ Next->Next->is(tok::colon)))) {
+ // This handles a special macro in ObjC code where selectors including
+ // the colon are passed as macro arguments.
+ Tok->setType(TT_ObjCSelector);
+ }
+ break;
+ case tok::pipe:
+ case tok::amp:
+ // | and & in declarations/type expressions represent union and
+ // intersection types, respectively.
+ if (Style.isJavaScript() && !Contexts.back().IsExpression)
+ Tok->setType(TT_JsTypeOperator);
+ break;
+ case tok::kw_if:
+ if (Style.isTableGen()) {
+ // In TableGen it has the form 'if' <value> 'then'.
+ if (!parseTableGenValue())
+ return false;
+ if (CurrentToken && CurrentToken->is(Keywords.kw_then))
+ next(); // skip then
+ break;
+ }
+ if (CurrentToken &&
+ CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) {
+ next();
+ }
+ IsIf = true;
+ [[fallthrough]];
+ case tok::kw_while:
+ if (CurrentToken && CurrentToken->is(tok::l_paren)) {
+ next();
+ if (!parseParens(IsIf))
+ return false;
+ }
+ break;
+ case tok::kw_for:
+ if (Style.isJavaScript()) {
+ // x.for and {for: ...}
+ if ((Prev && Prev->is(tok::period)) || (Next && Next->is(tok::colon)))
+ break;
+ // JS' for await ( ...
+ if (CurrentToken && CurrentToken->is(Keywords.kw_await))
+ next();
+ }
+ if (IsCpp && CurrentToken && CurrentToken->is(tok::kw_co_await))
+ next();
+ Contexts.back().ColonIsForRangeExpr = true;
+ if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
+ return false;
+ next();
+ if (!parseParens())
+ return false;
+ break;
+ case tok::l_paren:
+ // When faced with 'operator()()', the kw_operator handler incorrectly
+ // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
+ // the first two parens OverloadedOperators and the second l_paren an
+ // OverloadedOperatorLParen.
+ if (Prev && Prev->is(tok::r_paren) && Prev->MatchingParen &&
+ Prev->MatchingParen->is(TT_OverloadedOperatorLParen)) {
+ Prev->setType(TT_OverloadedOperator);
+ Prev->MatchingParen->setType(TT_OverloadedOperator);
+ Tok->setType(TT_OverloadedOperatorLParen);
+ }
+
+ if (Style.isVerilog()) {
+ // Identify the parameter list and port list in a module instantiation.
+ // This is still needed when we already have
+ // UnwrappedLineParser::parseVerilogHierarchyHeader because that
+ // function is only responsible for the definition, not the
+ // instantiation.
+ auto IsInstancePort = [&]() {
+ const FormatToken *PrevPrev;
+ // In the following example all 4 left parentheses will be treated as
+ // 'TT_VerilogInstancePortLParen'.
+ //
+ // module_x instance_1(port_1); // Case A.
+ // module_x #(parameter_1) // Case B.
+ // instance_2(port_1), // Case C.
+ // instance_3(port_1); // Case D.
+ if (!Prev || !(PrevPrev = Prev->getPreviousNonComment()))
+ return false;
+ // Case A.
+ if (Keywords.isVerilogIdentifier(*Prev) &&
+ Keywords.isVerilogIdentifier(*PrevPrev)) {
+ return true;
+ }
+ // Case B.
+ if (Prev->is(Keywords.kw_verilogHash) &&
+ Keywords.isVerilogIdentifier(*PrevPrev)) {
+ return true;
+ }
+ // Case C.
+ if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::r_paren))
+ return true;
+ // Case D.
+ if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::comma)) {
+ const FormatToken *PrevParen = PrevPrev->getPreviousNonComment();
+ if (PrevParen && PrevParen->is(tok::r_paren) &&
+ PrevParen->MatchingParen &&
+ PrevParen->MatchingParen->is(TT_VerilogInstancePortLParen)) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ if (IsInstancePort())
+ Tok->setType(TT_VerilogInstancePortLParen);
+ }
+
+ if (!parseParens())
+ return false;
+ if (Line.MustBeDeclaration && Contexts.size() == 1 &&
+ !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
+ !Line.startsWith(tok::l_paren) &&
+ Tok->isNoneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen)) {
+ if (!Prev ||
+ (!Prev->isAttribute() &&
+ Prev->isNoneOf(TT_RequiresClause, TT_LeadingJavaAnnotation,
+ TT_BinaryOperator))) {
+ Line.MightBeFunctionDecl = true;
+ Tok->MightBeFunctionDeclParen = true;
+ }
+ }
+ break;
+ case tok::l_square:
+ if (Style.isTableGen())
+ Tok->setType(TT_TableGenListOpener);
+ if (!parseSquare())
+ return false;
+ break;
+ case tok::l_brace:
+ if (IsCpp) {
+ if (Tok->is(TT_RequiresExpressionLBrace))
+ Line.Type = LT_RequiresExpression;
+ } else if (Style.isTextProto()) {
+ if (Prev && Prev->isNot(TT_DictLiteral))
+ Prev->setType(TT_SelectorName);
+ }
+ Scopes.push_back(getScopeType(*Tok));
+ if (!parseBrace())
+ return false;
+ break;
+ case tok::less:
+ if (parseAngle()) {
+ Tok->setType(TT_TemplateOpener);
+ // In TT_Proto, we must distignuish between:
+ // map<key, value>
+ // msg < item: data >
+ // msg: < item: data >
+ // In TT_TextProto, map<key, value> does not occur.
+ if (Style.isTextProto() ||
+ (Style.Language == FormatStyle::LK_Proto && Prev &&
+ Prev->isOneOf(TT_SelectorName, TT_DictLiteral))) {
+ Tok->setType(TT_DictLiteral);
+ if (Prev && Prev->isNot(TT_DictLiteral))
+ Prev->setType(TT_SelectorName);
+ }
+ if (Style.isTableGen())
+ Tok->setType(TT_TemplateOpener);
+ } else {
+ Tok->setType(TT_BinaryOperator);
+ NonTemplateLess.insert(Tok);
+ CurrentToken = Tok;
+ next();
+ }
+ break;
+ case tok::r_paren:
+ case tok::r_square:
+ return false;
+ case tok::r_brace:
+ // Don't pop scope when encountering unbalanced r_brace.
+ if (!Scopes.empty())
+ Scopes.pop_back();
+ // Lines can start with '}'.
+ if (Prev)
+ return false;
+ break;
+ case tok::greater:
+ if (!Style.isTextProto() && Tok->is(TT_Unknown))
+ Tok->setType(TT_BinaryOperator);
+ if (Prev && Prev->is(TT_TemplateCloser))
+ Tok->SpacesRequiredBefore = 1;
+ break;
+ case tok::kw_operator:
+ if (Style.isProto())
+ break;
+ // Handle C++ user-defined conversion function.
+ if (IsCpp && CurrentToken) {
+ const auto *Info = CurrentToken->Tok.getIdentifierInfo();
+ // What follows Tok is an identifier or a non-operator keyword.
+ if (Info && !(CurrentToken->isPlacementOperator() ||
+ CurrentToken->is(tok::kw_co_await) ||
+ Info->isCPlusPlusOperatorKeyword())) {
+ FormatToken *LParen;
+ if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
+ tok::kw_auto, tok::r_paren)) {
+ // Skip `decltype(auto)`.
+ LParen = CurrentToken->Next->Next->Next->Next;
+ } else {
+ // Skip to l_paren.
+ for (LParen = CurrentToken->Next;
+ LParen && LParen->isNot(tok::l_paren); LParen = LParen->Next) {
+ if (LParen->isPointerOrReference())
+ LParen->setFinalizedType(TT_PointerOrReference);
+ }
+ }
+ if (LParen && LParen->is(tok::l_paren)) {
+ if (!Contexts.back().IsExpression) {
+ Tok->setFinalizedType(TT_FunctionDeclarationName);
+ LParen->setFinalizedType(TT_FunctionDeclarationLParen);
+ }
+ break;
+ }
+ }
+ }
+ while (CurrentToken &&
+ CurrentToken->isNoneOf(tok::l_paren, tok::semi, tok::r_paren)) {
+ if (CurrentToken->isOneOf(tok::star, tok::amp))
+ CurrentToken->setType(TT_PointerOrReference);
+ auto Next = CurrentToken->getNextNonComment();
+ if (!Next)
+ break;
+ if (Next->is(tok::less))
+ next();
+ else
+ consumeToken();
+ if (!CurrentToken)
+ break;
+ auto Previous = CurrentToken->getPreviousNonComment();
+ assert(Previous);
+ if (CurrentToken->is(tok::comma) && Previous->isNot(tok::kw_operator))
+ break;
+ if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator, tok::comma,
+ tok::arrow) ||
+ Previous->isPointerOrReference() ||
+ // User defined literal.
+ Previous->TokenText.starts_with("\"\"")) {
+ Previous->setType(TT_OverloadedOperator);
+ if (CurrentToken->isOneOf(tok::less, tok::greater))
+ break;
+ }
+ }
+ if (CurrentToken && CurrentToken->is(tok::l_paren))
+ CurrentToken->setType(TT_OverloadedOperatorLParen);
+ if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
+ CurrentToken->Previous->setType(TT_OverloadedOperator);
+ break;
+ case tok::question:
+ if (Style.isJavaScript() && Next &&
+ Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
+ tok::r_brace, tok::r_square)) {
+ // Question marks before semicolons, colons, etc. indicate optional
+ // types (fields, parameters), e.g.
+ // function(x?: string, y?) {...}
+ // class X { y?; }
+ Tok->setType(TT_JsTypeOptionalQuestion);
+ break;
+ }
+ // Declarations cannot be conditional expressions, this can only be part
+ // of a type declaration.
+ if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
+ Style.isJavaScript()) {
+ break;
+ }
+ if (Style.isCSharp()) {
+ // `Type?)`, `Type?>`, `Type? name;`, and `Type? name =` can only be
+ // nullable types.
+ if (Next && (Next->isOneOf(tok::r_paren, tok::greater) ||
+ Next->startsSequence(tok::identifier, tok::semi) ||
+ Next->startsSequence(tok::identifier, tok::equal))) {
+ Tok->setType(TT_CSharpNullable);
+ break;
+ }
+
+ // Line.MustBeDeclaration will be true for `Type? name;`.
+ // But not
+ // cond ? "A" : "B";
+ // cond ? id : "B";
+ // cond ? cond2 ? "A" : "B" : "C";
+ if (!Contexts.back().IsExpression && Line.MustBeDeclaration &&
+ (!Next || Next->isNoneOf(tok::identifier, tok::string_literal) ||
+ !Next->Next || Next->Next->isNoneOf(tok::colon, tok::question))) {
+ Tok->setType(TT_CSharpNullable);
+ break;
+ }
+ }
+ parseConditional();
+ break;
+ case tok::kw_template:
+ parseTemplateDeclaration();
+ break;
+ case tok::comma:
+ switch (Contexts.back().ContextType) {
+ case Context::CtorInitializer:
+ Tok->setType(TT_CtorInitializerComma);
+ break;
+ case Context::InheritanceList:
+ Tok->setType(TT_InheritanceComma);
+ break;
+ case Context::VerilogInstancePortList:
+ Tok->setType(TT_VerilogInstancePortComma);
+ break;
+ default:
+ if (Style.isVerilog() && Contexts.size() == 1 &&
+ Line.startsWith(Keywords.kw_assign)) {
+ Tok->setFinalizedType(TT_VerilogAssignComma);
+ } else if (Contexts.back().FirstStartOfName &&
+ (Contexts.size() == 1 || startsWithInitStatement(Line))) {
+ Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
+ Line.IsMultiVariableDeclStmt = true;
+ }
+ break;
+ }
+ if (Contexts.back().ContextType == Context::ForEachMacro)
+ Contexts.back().IsExpression = true;
+ break;
+ case tok::kw_default:
+ // Unindent case labels.
+ if (Style.isVerilog() && Keywords.isVerilogEndOfLabel(*Tok) &&
+ (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))) {
+ --Line.Level;
+ }
+ break;
+ case tok::identifier:
+ if (Tok->isOneOf(Keywords.kw___has_include,
+ Keywords.kw___has_include_next)) {
+ parseHasInclude();
+ }
+ if (IsCpp) {
+ if (Next && Next->is(tok::l_paren) && Prev &&
+ Prev->isOneOf(tok::kw___cdecl, tok::kw___stdcall,
+ tok::kw___fastcall, tok::kw___thiscall,
+ tok::kw___regcall, tok::kw___vectorcall)) {
+ Tok->setFinalizedType(TT_FunctionDeclarationName);
+ Next->setFinalizedType(TT_FunctionDeclarationLParen);
+ }
+ } else if (Style.isCSharp()) {
+ if (Tok->is(Keywords.kw_where) && Next && Next->isNot(tok::l_paren)) {
+ Tok->setType(TT_CSharpGenericTypeConstraint);
+ parseCSharpGenericTypeConstraint();
+ if (!Prev)
+ Line.IsContinuation = true;
+ }
+ } else if (Style.isTableGen()) {
+ if (Tok->is(Keywords.kw_assert)) {
+ if (!parseTableGenValue())
+ return false;
+ } else if (Tok->isOneOf(Keywords.kw_def, Keywords.kw_defm) &&
+ (!Next || Next->isNoneOf(tok::colon, tok::l_brace))) {
+ // The case NameValue appears.
+ if (!parseTableGenValue(true))
+ return false;
+ }
+ }
+ if (Style.AllowBreakBeforeQtProperty &&
+ Contexts.back().ContextType == Context::QtProperty &&
+ Tok->isQtProperty()) {
+ Tok->setFinalizedType(TT_QtProperty);
+ }
+ break;
+ case tok::arrow:
+ if (Tok->isNot(TT_LambdaArrow) && Prev && Prev->is(tok::kw_noexcept))
+ Tok->setType(TT_TrailingReturnArrow);
+ break;
+ case tok::equal:
+ // In TableGen, there must be a value after "=";
+ if (Style.isTableGen() && !parseTableGenValue())
+ return false;
+ break;
+ default:
+ break;
+ }
+ return true;
+ }
+
+ void parseCSharpGenericTypeConstraint() {
+ int OpenAngleBracketsCount = 0;
+ while (CurrentToken) {
+ if (CurrentToken->is(tok::less)) {
+ // parseAngle is too greedy and will consume the whole line.
+ CurrentToken->setType(TT_TemplateOpener);
+ ++OpenAngleBracketsCount;
+ next();
+ } else if (CurrentToken->is(tok::greater)) {
+ CurrentToken->setType(TT_TemplateCloser);
+ --OpenAngleBracketsCount;
+ next();
+ } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) {
+ // We allow line breaks after GenericTypeConstraintComma's
+ // so do not flag commas in Generics as GenericTypeConstraintComma's.
+ CurrentToken->setType(TT_CSharpGenericTypeConstraintComma);
+ next();
+ } else if (CurrentToken->is(Keywords.kw_where)) {
+ CurrentToken->setType(TT_CSharpGenericTypeConstraint);
+ next();
+ } else if (CurrentToken->is(tok::colon)) {
+ CurrentToken->setType(TT_CSharpGenericTypeConstraintColon);
+ next();
+ } else {
+ next();
+ }
+ }
+ }
+
+ void parseIncludeDirective() {
+ if (CurrentToken && CurrentToken->is(tok::less)) {
+ next();
+ while (CurrentToken) {
+ // Mark tokens up to the trailing line comments as implicit string
+ // literals.
+ if (CurrentToken->isNot(tok::comment) &&
+ !CurrentToken->TokenText.starts_with("//")) {
+ CurrentToken->setType(TT_ImplicitStringLiteral);
+ }
+ next();
+ }
+ }
+ }
+
+ void parseWarningOrError() {
+ next();
+ // We still want to format the whitespace left of the first token of the
+ // warning or error.
+ next();
+ while (CurrentToken) {
+ CurrentToken->setType(TT_ImplicitStringLiteral);
+ next();
+ }
+ }
+
+ void parsePragma() {
+ next(); // Consume "pragma".
+ if (CurrentToken &&
+ CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option,
+ Keywords.kw_region)) {
+ bool IsMarkOrRegion =
+ CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_region);
+ next();
+ next(); // Consume first token (so we fix leading whitespace).
+ while (CurrentToken) {
+ if (IsMarkOrRegion || CurrentToken->Previous->is(TT_BinaryOperator))
+ CurrentToken->setType(TT_ImplicitStringLiteral);
+ next();
+ }
+ }
+ }
+
+ void parseHasInclude() {
+ if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
+ return;
+ next(); // '('
+ parseIncludeDirective();
+ next(); // ')'
+ }
+
+ LineType parsePreprocessorDirective() {
+ bool IsFirstToken = CurrentToken->IsFirst;
+ LineType Type = LT_PreprocessorDirective;
+ next();
+ if (!CurrentToken)
+ return Type;
+
+ if (Style.isJavaScript() && IsFirstToken) {
+ // JavaScript files can contain shebang lines of the form:
+ // #!/usr/bin/env node
+ // Treat these like C++ #include directives.
+ while (CurrentToken) {
+ // Tokens cannot be comments here.
+ CurrentToken->setType(TT_ImplicitStringLiteral);
+ next();
+ }
+ return LT_ImportStatement;
+ }
+
+ if (CurrentToken->is(tok::numeric_constant)) {
+ CurrentToken->SpacesRequiredBefore = 1;
+ return Type;
+ }
+ // Hashes in the middle of a line can lead to any strange token
+ // sequence.
+ if (!CurrentToken->Tok.getIdentifierInfo())
+ return Type;
+ // In Verilog macro expansions start with a backtick just like preprocessor
+ // directives. Thus we stop if the word is not a preprocessor directive.
+ if (Style.isVerilog() && !Keywords.isVerilogPPDirective(*CurrentToken))
+ return LT_Invalid;
+ switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
+ case tok::pp_include:
+ case tok::pp_include_next:
+ case tok::pp_import:
+ next();
+ parseIncludeDirective();
+ Type = LT_ImportStatement;
+ break;
+ case tok::pp_error:
+ case tok::pp_warning:
+ parseWarningOrError();
+ break;
+ case tok::pp_pragma:
+ parsePragma();
+ break;
+ case tok::pp_if:
+ case tok::pp_elif:
+ Contexts.back().IsExpression = true;
+ next();
+ if (CurrentToken)
+ CurrentToken->SpacesRequiredBefore = 1;
+ parseLine();
+ break;
+ default:
+ break;
+ }
+ while (CurrentToken) {
+ FormatToken *Tok = CurrentToken;
+ next();
+ if (Tok->is(tok::l_paren)) {
+ parseParens();
+ } else if (Tok->isOneOf(Keywords.kw___has_include,
+ Keywords.kw___has_include_next)) {
+ parseHasInclude();
+ }
+ }
+ return Type;
+ }
+
+public:
+ LineType parseLine() {
+ if (!CurrentToken)
+ return LT_Invalid;
+ NonTemplateLess.clear();
+ if (!Line.InMacroBody && CurrentToken->is(tok::hash)) {
+ // We were not yet allowed to use C++17 optional when this was being
+ // written. So we used LT_Invalid to mark that the line is not a
+ // preprocessor directive.
+ auto Type = parsePreprocessorDirective();
+ if (Type != LT_Invalid)
+ return Type;
+ }
+
+ // Directly allow to 'import <string-literal>' to support protocol buffer
+ // definitions (github.com/google/protobuf) or missing "#" (either way we
+ // should not break the line).
+ IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
+ if ((Style.isJava() && CurrentToken->is(Keywords.kw_package)) ||
+ (!Style.isVerilog() && Info &&
+ Info->getPPKeywordID() == tok::pp_import && CurrentToken->Next &&
+ CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
+ tok::kw_static))) {
+ next();
+ parseIncludeDirective();
+ return LT_ImportStatement;
+ }
+
+ // If this line starts and ends in '<' and '>', respectively, it is likely
+ // part of "#define <a/b.h>".
+ if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
+ parseIncludeDirective();
+ return LT_ImportStatement;
+ }
+
+ // In .proto files, top-level options and package statements are very
+ // similar to import statements and should not be line-wrapped.
+ if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
+ CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
+ next();
+ if (CurrentToken && CurrentToken->is(tok::identifier)) {
+ while (CurrentToken)
+ next();
+ return LT_ImportStatement;
+ }
+ }
+
+ bool KeywordVirtualFound = false;
+ bool ImportStatement = false;
+
+ // import {...} from '...';
+ if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import))
+ ImportStatement = true;
+
+ while (CurrentToken) {
+ if (CurrentToken->is(tok::kw_virtual))
+ KeywordVirtualFound = true;
+ if (Style.isJavaScript()) {
+ // export {...} from '...';
+ // An export followed by "from 'some string';" is a re-export from
+ // another module identified by a URI and is treated as a
+ // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
+ // Just "export {...};" or "export class ..." should not be treated as
+ // an import in this sense.
+ if (Line.First->is(tok::kw_export) &&
+ CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
+ CurrentToken->Next->isStringLiteral()) {
+ ImportStatement = true;
+ }
+ if (isClosureImportStatement(*CurrentToken))
+ ImportStatement = true;
+ }
+ if (!consumeToken())
+ return LT_Invalid;
+ }
+ if (const auto Type = Line.Type; Type == LT_AccessModifier ||
+ Type == LT_RequiresExpression ||
+ Type == LT_SimpleRequirement) {
+ return Type;
+ }
+ if (KeywordVirtualFound)
+ return LT_VirtualFunctionDecl;
+ if (ImportStatement)
+ return LT_ImportStatement;
+
+ if (Line.startsWith(TT_ObjCMethodSpecifier)) {
+ if (Contexts.back().FirstObjCSelectorName) {
+ Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
+ Contexts.back().LongestObjCSelectorName;
+ }
+ return LT_ObjCMethodDecl;
+ }
+
+ for (const auto &ctx : Contexts)
+ if (ctx.ContextType == Context::StructArrayInitializer)
+ return LT_ArrayOfStructInitializer;
+
+ return LT_Other;
+ }
+
+private:
+ bool isClosureImportStatement(const FormatToken &Tok) {
+ // FIXME: Closure-library specific stuff should not be hard-coded but be
+ // configurable.
+ return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
+ Tok.Next->Next &&
+ (Tok.Next->Next->TokenText == "module" ||
+ Tok.Next->Next->TokenText == "provide" ||
+ Tok.Next->Next->TokenText == "require" ||
+ Tok.Next->Next->TokenText == "requireType" ||
+ Tok.Next->Next->TokenText == "forwardDeclare") &&
+ Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
+ }
+
+ void resetTokenMetadata() {
+ if (!CurrentToken)
+ return;
+
+ // Reset token type in case we have already looked at it and then
+ // recovered from an error (e.g. failure to find the matching >).
+ if (!CurrentToken->isTypeFinalized() &&
+ CurrentToken->isNoneOf(
+ TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
+ TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace,
+ TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow,
+ TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
+ TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
+ TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
+ TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace,
+ TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause,
+ TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
+ TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
+ TT_CompoundRequirementLBrace, TT_BracedListLBrace,
+ TT_FunctionLikeMacro)) {
+ CurrentToken->setType(TT_Unknown);
+ }
+ CurrentToken->Role.reset();
+ CurrentToken->MatchingParen = nullptr;
+ CurrentToken->FakeLParens.clear();
+ CurrentToken->FakeRParens = 0;
+ }
+
+ void next() {
+ if (!CurrentToken)
+ return;
+
+ CurrentToken->NestingLevel = Contexts.size() - 1;
+ CurrentToken->BindingStrength = Contexts.back().BindingStrength;
+ modifyContext(*CurrentToken);
+ determineTokenType(*CurrentToken);
+ CurrentToken = CurrentToken->Next;
+
+ resetTokenMetadata();
+ }
+
+ /// A struct to hold information valid in a specific context, e.g.
+ /// a pair of parenthesis.
+ struct Context {
+ Context(tok::TokenKind ContextKind, unsigned BindingStrength,
+ bool IsExpression)
+ : ContextKind(ContextKind), BindingStrength(BindingStrength),
+ IsExpression(IsExpression) {}
+
+ tok::TokenKind ContextKind;
+ unsigned BindingStrength;
+ bool IsExpression;
+ unsigned LongestObjCSelectorName = 0;
+ bool ColonIsForRangeExpr = false;
+ bool ColonIsDictLiteral = false;
+ bool ColonIsObjCMethodExpr = false;
+ FormatToken *FirstObjCSelectorName = nullptr;
+ FormatToken *FirstStartOfName = nullptr;
+ bool CanBeExpression = true;
+ bool CaretFound = false;
+ bool InCpp11AttributeSpecifier = false;
+ bool InCSharpAttributeSpecifier = false;
+ bool InStaticAssertFirstArgument = false;
+ bool VerilogAssignmentFound = false;
+ // Whether the braces may mean concatenation instead of structure or array
+ // literal.
+ bool VerilogMayBeConcatenation = false;
+ bool IsTableGenDAGArgList = false;
+ bool IsTableGenBangOpe = false;
+ bool IsTableGenCondOpe = false;
+ enum {
+ Unknown,
+ // Like the part after `:` in a constructor.
+ // Context(...) : IsExpression(IsExpression)
+ CtorInitializer,
+ // Like in the parentheses in a foreach.
+ ForEachMacro,
+ // Like the inheritance list in a class declaration.
+ // class Input : public IO
+ InheritanceList,
+ // Like in the braced list.
+ // int x[] = {};
+ StructArrayInitializer,
+ // Like in `static_cast<int>`.
+ TemplateArgument,
+ // C11 _Generic selection.
+ C11GenericSelection,
+ QtProperty,
+ // Like in the outer parentheses in `ffnand ff1(.q());`.
+ VerilogInstancePortList,
+ } ContextType = Unknown;
+ };
+
+ /// Puts a new \c Context onto the stack \c Contexts for the lifetime
+ /// of each instance.
+ struct ScopedContextCreator {
+ AnnotatingParser &P;
+
+ ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
+ unsigned Increase)
+ : P(P) {
+ P.Contexts.push_back(Context(ContextKind,
+ P.Contexts.back().BindingStrength + Increase,
+ P.Contexts.back().IsExpression));
+ }
+
+ ~ScopedContextCreator() {
+ if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
+ if (P.Contexts.back().ContextType == Context::StructArrayInitializer) {
+ P.Contexts.pop_back();
+ P.Contexts.back().ContextType = Context::StructArrayInitializer;
+ return;
+ }
+ }
+ P.Contexts.pop_back();
+ }
+ };
+
+ void modifyContext(const FormatToken &Current) {
+ auto AssignmentStartsExpression = [&]() {
+ if (Current.getPrecedence() != prec::Assignment)
+ return false;
+
+ if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
+ return false;
+ if (Line.First->is(tok::kw_template)) {
+ assert(Current.Previous);
+ if (Current.Previous->is(tok::kw_operator)) {
+ // `template ... operator=` cannot be an expression.
+ return false;
+ }
+
+ // `template` keyword can start a variable template.
+ const FormatToken *Tok = Line.First->getNextNonComment();
+ assert(Tok); // Current token is on the same line.
+ if (Tok->isNot(TT_TemplateOpener)) {
+ // Explicit template instantiations do not have `<>`.
+ return false;
+ }
+
+ // This is the default value of a template parameter, determine if it's
+ // type or non-type.
+ if (Contexts.back().ContextKind == tok::less) {
+ assert(Current.Previous->Previous);
+ return Current.Previous->Previous->isNoneOf(tok::kw_typename,
+ tok::kw_class);
+ }
+
+ Tok = Tok->MatchingParen;
+ if (!Tok)
+ return false;
+ Tok = Tok->getNextNonComment();
+ if (!Tok)
+ return false;
+
+ if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_struct,
+ tok::kw_using)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ // Type aliases use `type X = ...;` in TypeScript and can be exported
+ // using `export type ...`.
+ if (Style.isJavaScript() &&
+ (Line.startsWith(Keywords.kw_type, tok::identifier) ||
+ Line.startsWith(tok::kw_export, Keywords.kw_type,
+ tok::identifier))) {
+ return false;
+ }
+
+ return !Current.Previous || Current.Previous->isNot(tok::kw_operator);
+ };
+
+ if (AssignmentStartsExpression()) {
+ Contexts.back().IsExpression = true;
+ if (!Line.startsWith(TT_UnaryOperator)) {
+ for (FormatToken *Previous = Current.Previous;
+ Previous && Previous->Previous &&
+ Previous->Previous->isNoneOf(tok::comma, tok::semi);
+ Previous = Previous->Previous) {
+ if (Previous->isOneOf(tok::r_square, tok::r_paren, tok::greater)) {
+ Previous = Previous->MatchingParen;
+ if (!Previous)
+ break;
+ }
+ if (Previous->opensScope())
+ break;
+ if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
+ Previous->isPointerOrReference() && Previous->Previous &&
+ Previous->Previous->isNot(tok::equal)) {
+ Previous->setType(TT_PointerOrReference);
+ }
+ }
+ }
+ } else if (Current.is(tok::lessless) &&
+ (!Current.Previous ||
+ Current.Previous->isNot(tok::kw_operator))) {
+ Contexts.back().IsExpression = true;
+ } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
+ Contexts.back().IsExpression = true;
+ } else if (Current.is(TT_TrailingReturnArrow)) {
+ Contexts.back().IsExpression = false;
+ } else if (Current.isOneOf(TT_LambdaArrow, Keywords.kw_assert)) {
+ Contexts.back().IsExpression = Style.isJava();
+ } else if (Current.Previous &&
+ Current.Previous->is(TT_CtorInitializerColon)) {
+ Contexts.back().IsExpression = true;
+ Contexts.back().ContextType = Context::CtorInitializer;
+ } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
+ Contexts.back().ContextType = Context::InheritanceList;
+ } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
+ for (FormatToken *Previous = Current.Previous;
+ Previous && Previous->isOneOf(tok::star, tok::amp);
+ Previous = Previous->Previous) {
+ Previous->setType(TT_PointerOrReference);
+ }
+ if (Line.MustBeDeclaration &&
+ Contexts.front().ContextType != Context::CtorInitializer) {
+ Contexts.back().IsExpression = false;
+ }
+ } else if (Current.is(tok::kw_new)) {
+ Contexts.back().CanBeExpression = false;
+ } else if (Current.is(tok::semi) ||
+ (Current.is(tok::exclaim) && Current.Previous &&
+ Current.Previous->isNot(tok::kw_operator))) {
+ // This should be the condition or increment in a for-loop.
+ // But not operator !() (can't use TT_OverloadedOperator here as its not
+ // been annotated yet).
+ Contexts.back().IsExpression = true;
+ }
+ }
+
+ static FormatToken *untilMatchingParen(FormatToken *Current) {
+ // Used when `MatchingParen` is not yet established.
+ int ParenLevel = 0;
+ while (Current) {
+ if (Current->is(tok::l_paren))
+ ++ParenLevel;
+ if (Current->is(tok::r_paren))
+ --ParenLevel;
+ if (ParenLevel < 1)
+ break;
+ Current = Current->Next;
+ }
+ return Current;
+ }
+
+ static bool isDeductionGuide(FormatToken &Current) {
+ // Look for a deduction guide template<T> A(...) -> A<...>;
+ if (Current.Previous && Current.Previous->is(tok::r_paren) &&
+ Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
+ // Find the TemplateCloser.
+ FormatToken *TemplateCloser = Current.Next->Next;
+ int NestingLevel = 0;
+ while (TemplateCloser) {
+ // Skip over an expressions in parens A<(3 < 2)>;
+ if (TemplateCloser->is(tok::l_paren)) {
+ // No Matching Paren yet so skip to matching paren
+ TemplateCloser = untilMatchingParen(TemplateCloser);
+ if (!TemplateCloser)
+ break;
+ }
+ if (TemplateCloser->is(tok::less))
+ ++NestingLevel;
+ if (TemplateCloser->is(tok::greater))
+ --NestingLevel;
+ if (NestingLevel < 1)
+ break;
+ TemplateCloser = TemplateCloser->Next;
+ }
+ // Assuming we have found the end of the template ensure its followed
+ // with a semi-colon.
+ if (TemplateCloser && TemplateCloser->Next &&
+ TemplateCloser->Next->is(tok::semi) &&
+ Current.Previous->MatchingParen) {
+ // Determine if the identifier `A` prior to the A<..>; is the same as
+ // prior to the A(..)
+ FormatToken *LeadingIdentifier =
+ Current.Previous->MatchingParen->Previous;
+
+ return LeadingIdentifier &&
+ LeadingIdentifier->TokenText == Current.Next->TokenText;
+ }
+ }
+ return false;
+ }
+
+ void determineTokenType(FormatToken &Current) {
+ if (Current.isNot(TT_Unknown)) {
+ // The token type is already known.
+ return;
+ }
+
+ if ((Style.isJavaScript() || Style.isCSharp()) &&
+ Current.is(tok::exclaim)) {
+ if (Current.Previous) {
+ bool IsIdentifier =
+ Style.isJavaScript()
+ ? Keywords.isJavaScriptIdentifier(
+ *Current.Previous, /* AcceptIdentifierName= */ true)
+ : Current.Previous->is(tok::identifier);
+ if (IsIdentifier ||
+ Current.Previous->isOneOf(
+ tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square,
+ tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type,
+ Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) ||
+ Current.Previous->Tok.isLiteral()) {
+ Current.setType(TT_NonNullAssertion);
+ return;
+ }
+ }
+ if (Current.Next &&
+ Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
+ Current.setType(TT_NonNullAssertion);
+ return;
+ }
+ }
+
+ // Line.MightBeFunctionDecl can only be true after the parentheses of a
+ // function declaration have been found. In this case, 'Current' is a
+ // trailing token of this declaration and thus cannot be a name.
+ if ((Style.isJavaScript() || Style.isJava()) &&
+ Current.is(Keywords.kw_instanceof)) {
+ Current.setType(TT_BinaryOperator);
+ } else if (isStartOfName(Current) &&
+ (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
+ Contexts.back().FirstStartOfName = &Current;
+ Current.setType(TT_StartOfName);
+ } else if (Current.is(tok::semi)) {
+ // Reset FirstStartOfName after finding a semicolon so that a for loop
+ // with multiple increment statements is not confused with a for loop
+ // having multiple variable declarations.
+ Contexts.back().FirstStartOfName = nullptr;
+ } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
+ AutoFound = true;
+ } else if (Current.is(tok::arrow) && Style.isJava()) {
+ Current.setType(TT_LambdaArrow);
+ } else if (Current.is(tok::arrow) && Style.isVerilog()) {
+ // The implication operator.
+ Current.setType(TT_BinaryOperator);
+ } else if (Current.is(tok::arrow) && AutoFound &&
+ Line.MightBeFunctionDecl && Current.NestingLevel == 0 &&
+ Current.Previous->isNoneOf(tok::kw_operator, tok::identifier)) {
+ // not auto operator->() -> xxx;
+ Current.setType(TT_TrailingReturnArrow);
+ } else if (Current.is(tok::arrow) && Current.Previous &&
+ Current.Previous->is(tok::r_brace) &&
+ Current.Previous->is(BK_Block)) {
+ // Concept implicit conversion constraint needs to be treated like
+ // a trailing return type ... } -> <type>.
+ Current.setType(TT_TrailingReturnArrow);
+ } else if (isDeductionGuide(Current)) {
+ // Deduction guides trailing arrow " A(...) -> A<T>;".
+ Current.setType(TT_TrailingReturnArrow);
+ } else if (Current.isPointerOrReference()) {
+ Current.setType(determineStarAmpUsage(
+ Current,
+ (Contexts.back().CanBeExpression && Contexts.back().IsExpression) ||
+ Contexts.back().InStaticAssertFirstArgument,
+ Contexts.back().ContextType == Context::TemplateArgument));
+ } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret) ||
+ (Style.isVerilog() && Current.is(tok::pipe))) {
+ Current.setType(determinePlusMinusCaretUsage(Current));
+ if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
+ Contexts.back().CaretFound = true;
+ } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
+ Current.setType(determineIncrementUsage(Current));
+ } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
+ Current.setType(TT_UnaryOperator);
+ } else if (Current.is(tok::question)) {
+ if (Style.isJavaScript() && Line.MustBeDeclaration &&
+ !Contexts.back().IsExpression) {
+ // In JavaScript, `interface X { foo?(): bar; }` is an optional method
+ // on the interface, not a ternary expression.
+ Current.setType(TT_JsTypeOptionalQuestion);
+ } else if (Style.isTableGen()) {
+ // In TableGen, '?' is just an identifier like token.
+ Current.setType(TT_Unknown);
+ } else {
+ Current.setType(TT_ConditionalExpr);
+ }
+ } else if (Current.isBinaryOperator() &&
+ (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
+ (Current.isNot(tok::greater) && !Style.isTextProto())) {
+ if (Style.isVerilog()) {
+ if (Current.is(tok::lessequal) && Contexts.size() == 1 &&
+ !Contexts.back().VerilogAssignmentFound) {
+ // In Verilog `<=` is assignment if in its own statement. It is a
+ // statement instead of an expression, that is it can not be chained.
+ Current.ForcedPrecedence = prec::Assignment;
+ Current.setFinalizedType(TT_BinaryOperator);
+ }
+ if (Current.getPrecedence() == prec::Assignment)
+ Contexts.back().VerilogAssignmentFound = true;
+ }
+ Current.setType(TT_BinaryOperator);
+ } else if (Current.is(tok::comment)) {
+ if (Current.TokenText.starts_with("/*")) {
+ if (Current.TokenText.ends_with("*/")) {
+ Current.setType(TT_BlockComment);
+ } else {
+ // The lexer has for some reason determined a comment here. But we
+ // cannot really handle it, if it isn't properly terminated.
+ Current.Tok.setKind(tok::unknown);
+ }
+ } else {
+ Current.setType(TT_LineComment);
+ }
+ } else if (Current.is(tok::string_literal)) {
+ if (Style.isVerilog() && Contexts.back().VerilogMayBeConcatenation &&
+ Current.getPreviousNonComment() &&
+ Current.getPreviousNonComment()->isOneOf(tok::comma, tok::l_brace) &&
+ Current.getNextNonComment() &&
+ Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
+ Current.setType(TT_StringInConcatenation);
+ }
+ } else if (Current.is(tok::l_paren)) {
+ if (lParenStartsCppCast(Current))
+ Current.setType(TT_CppCastLParen);
+ } else if (Current.is(tok::r_paren)) {
+ if (rParenEndsCast(Current))
+ Current.setType(TT_CastRParen);
+ if (Current.MatchingParen && Current.Next &&
+ !Current.Next->isBinaryOperator() &&
+ Current.Next->isNoneOf(
+ tok::semi, tok::colon, tok::l_brace, tok::l_paren, tok::comma,
+ tok::period, tok::arrow, tok::coloncolon, tok::kw_noexcept)) {
+ if (FormatToken *AfterParen = Current.MatchingParen->Next;
+ AfterParen && AfterParen->isNot(tok::caret)) {
+ // Make sure this isn't the return type of an Obj-C block declaration.
+ if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
+ BeforeParen && BeforeParen->is(tok::identifier) &&
+ BeforeParen->isNot(TT_TypenameMacro) &&
+ BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
+ (!BeforeParen->Previous ||
+ BeforeParen->Previous->ClosesTemplateDeclaration ||
+ BeforeParen->Previous->ClosesRequiresClause)) {
+ Current.setType(TT_FunctionAnnotationRParen);
+ }
+ }
+ }
+ } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() &&
+ !Style.isJava()) {
+ // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
+ // marks declarations and properties that need special formatting.
+ switch (Current.Next->Tok.getObjCKeywordID()) {
+ case tok::objc_interface:
+ case tok::objc_implementation:
+ case tok::objc_protocol:
+ Current.setType(TT_ObjCDecl);
+ break;
+ case tok::objc_property:
+ Current.setType(TT_ObjCProperty);
+ break;
+ default:
+ break;
+ }
+ } else if (Current.is(tok::period)) {
+ FormatToken *PreviousNoComment = Current.getPreviousNonComment();
+ if (PreviousNoComment &&
+ PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) {
+ Current.setType(TT_DesignatedInitializerPeriod);
+ } else if (Style.isJava() && Current.Previous &&
+ Current.Previous->isOneOf(TT_JavaAnnotation,
+ TT_LeadingJavaAnnotation)) {
+ Current.setType(Current.Previous->getType());
+ }
+ } else if (canBeObjCSelectorComponent(Current) &&
+ // FIXME(bug 36976): ObjC return types shouldn't use
+ // TT_CastRParen.
+ Current.Previous && Current.Previous->is(TT_CastRParen) &&
+ Current.Previous->MatchingParen &&
+ Current.Previous->MatchingParen->Previous &&
+ Current.Previous->MatchingParen->Previous->is(
+ TT_ObjCMethodSpecifier)) {
+ // This is the first part of an Objective-C selector name. (If there's no
+ // colon after this, this is the only place which annotates the identifier
+ // as a selector.)
+ Current.setType(TT_SelectorName);
+ } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept,
+ tok::kw_requires) &&
+ Current.Previous &&
+ Current.Previous->isNoneOf(tok::equal, tok::at,
+ TT_CtorInitializerComma,
+ TT_CtorInitializerColon) &&
+ Line.MightBeFunctionDecl && Contexts.size() == 1) {
+ // Line.MightBeFunctionDecl can only be true after the parentheses of a
+ // function declaration have been found.
+ Current.setType(TT_TrailingAnnotation);
+ } else if ((Style.isJava() || Style.isJavaScript()) && Current.Previous) {
+ if (Current.Previous->is(tok::at) &&
+ Current.isNot(Keywords.kw_interface)) {
+ const FormatToken &AtToken = *Current.Previous;
+ const FormatToken *Previous = AtToken.getPreviousNonComment();
+ if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
+ Current.setType(TT_LeadingJavaAnnotation);
+ else
+ Current.setType(TT_JavaAnnotation);
+ } else if (Current.Previous->is(tok::period) &&
+ Current.Previous->isOneOf(TT_JavaAnnotation,
+ TT_LeadingJavaAnnotation)) {
+ Current.setType(Current.Previous->getType());
+ }
+ }
+ }
+
+ /// Take a guess at whether \p Tok starts a name of a function or
+ /// variable declaration.
+ ///
+ /// This is a heuristic based on whether \p Tok is an identifier following
+ /// something that is likely a type.
+ bool isStartOfName(const FormatToken &Tok) {
+ // Handled in ExpressionParser for Verilog.
+ if (Style.isVerilog())
+ return false;
+
+ if (!Tok.Previous || Tok.isNot(tok::identifier) || Tok.is(TT_ClassHeadName))
+ return false;
+
+ if (Tok.endsSequence(Keywords.kw_final, TT_ClassHeadName))
+ return false;
+
+ if ((Style.isJavaScript() || Style.isJava()) && Tok.is(Keywords.kw_extends))
+ return false;
+
+ if (const auto *NextNonComment = Tok.getNextNonComment();
+ (!NextNonComment && !Line.InMacroBody) ||
+ (NextNonComment &&
+ (NextNonComment->isPointerOrReference() ||
+ NextNonComment->isOneOf(TT_ClassHeadName, tok::string_literal) ||
+ (Line.InPragmaDirective && NextNonComment->is(tok::identifier))))) {
+ return false;
+ }
+
+ if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
+ Keywords.kw_as)) {
+ return false;
+ }
+ if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in))
+ return false;
+
+ // Skip "const" as it does not have an influence on whether this is a name.
+ FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
+
+ // For javascript const can be like "let" or "var"
+ if (!Style.isJavaScript())
+ while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
+ PreviousNotConst = PreviousNotConst->getPreviousNonComment();
+
+ if (!PreviousNotConst)
+ return false;
+
+ if (PreviousNotConst->ClosesRequiresClause)
+ return false;
+
+ if (Style.isTableGen()) {
+ // keywords such as let and def* defines names.
+ if (Keywords.isTableGenDefinition(*PreviousNotConst))
+ return true;
+ // Otherwise C++ style declarations is available only inside the brace.
+ if (Contexts.back().ContextKind != tok::l_brace)
+ return false;
+ }
+
+ bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
+ PreviousNotConst->Previous &&
+ PreviousNotConst->Previous->is(tok::hash);
+
+ if (PreviousNotConst->is(TT_TemplateCloser)) {
+ return PreviousNotConst && PreviousNotConst->MatchingParen &&
+ PreviousNotConst->MatchingParen->Previous &&
+ PreviousNotConst->MatchingParen->Previous->isNoneOf(
+ tok::period, tok::kw_template);
+ }
+
+ if ((PreviousNotConst->is(tok::r_paren) &&
+ PreviousNotConst->is(TT_TypeDeclarationParen)) ||
+ PreviousNotConst->is(TT_AttributeRParen)) {
+ return true;
+ }
+
+ // If is a preprocess keyword like #define.
+ if (IsPPKeyword)
+ return false;
+
+ // int a or auto a.
+ if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto) &&
+ PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
+ return true;
+ }
+
+ // *a or &a or &&a.
+ if (PreviousNotConst->is(TT_PointerOrReference) ||
+ PreviousNotConst->endsSequence(tok::coloncolon,
+ TT_PointerOrReference)) {
+ return true;
+ }
+
+ // MyClass a;
+ if (PreviousNotConst->isTypeName(LangOpts))
+ return true;
+
+ // type[] a in Java
+ if (Style.isJava() && PreviousNotConst->is(tok::r_square))
+ return true;
+
+ // const a = in JavaScript.
+ return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
+ }
+
+ /// Determine whether '(' is starting a C++ cast.
+ bool lParenStartsCppCast(const FormatToken &Tok) {
+ // C-style casts are only used in C++.
+ if (!IsCpp)
+ return false;
+
+ FormatToken *LeftOfParens = Tok.getPreviousNonComment();
+ if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) &&
+ LeftOfParens->MatchingParen) {
+ auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment();
+ if (Prev &&
+ Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast,
+ tok::kw_reinterpret_cast, tok::kw_static_cast)) {
+ // FIXME: Maybe we should handle identifiers ending with "_cast",
+ // e.g. any_cast?
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /// Determine whether ')' is ending a cast.
+ bool rParenEndsCast(const FormatToken &Tok) {
+ assert(Tok.is(tok::r_paren));
+
+ if (!Tok.MatchingParen || !Tok.Previous)
+ return false;
+
+ // C-style casts are only used in C++, C# and Java.
+ if (!IsCpp && !Style.isCSharp() && !Style.isJava())
+ return false;
+
+ const auto *LParen = Tok.MatchingParen;
+ const auto *BeforeRParen = Tok.Previous;
+ const auto *AfterRParen = Tok.Next;
+
+ // Empty parens aren't casts and there are no casts at the end of the line.
+ if (BeforeRParen == LParen || !AfterRParen)
+ return false;
+
+ if (LParen->isOneOf(TT_OverloadedOperatorLParen, TT_FunctionTypeLParen))
+ return false;
+
+ auto *LeftOfParens = LParen->getPreviousNonComment();
+ if (LeftOfParens) {
+ // If there is a closing parenthesis left of the current
+ // parentheses, look past it as these might be chained casts.
+ if (LeftOfParens->is(tok::r_paren) &&
+ LeftOfParens->isNot(TT_CastRParen)) {
+ if (!LeftOfParens->MatchingParen ||
+ !LeftOfParens->MatchingParen->Previous) {
+ return false;
+ }
+ LeftOfParens = LeftOfParens->MatchingParen->Previous;
+ }
+
+ if (LeftOfParens->is(tok::r_square)) {
+ // delete[] (void *)ptr;
+ auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
+ if (Tok->isNot(tok::r_square))
+ return nullptr;
+
+ Tok = Tok->getPreviousNonComment();
+ if (!Tok || Tok->isNot(tok::l_square))
+ return nullptr;
+
+ Tok = Tok->getPreviousNonComment();
+ if (!Tok || Tok->isNot(tok::kw_delete))
+ return nullptr;
+ return Tok;
+ };
+ if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
+ LeftOfParens = MaybeDelete;
+ }
+
+ // The Condition directly below this one will see the operator arguments
+ // as a (void *foo) cast.
+ // void operator delete(void *foo) ATTRIB;
+ if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
+ LeftOfParens->Previous->is(tok::kw_operator)) {
+ return false;
+ }
+
+ // If there is an identifier (or with a few exceptions a keyword) right
+ // before the parentheses, this is unlikely to be a cast.
+ if (LeftOfParens->Tok.getIdentifierInfo() &&
+ LeftOfParens->isNoneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
+ tok::kw_delete, tok::kw_throw)) {
+ return false;
+ }
+
+ // Certain other tokens right before the parentheses are also signals that
+ // this cannot be a cast.
+ if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
+ TT_TemplateCloser, tok::ellipsis)) {
+ return false;
+ }
+ }
+
+ if (AfterRParen->is(tok::question) ||
+ (AfterRParen->is(tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) {
+ return false;
+ }
+
+ // `foreach((A a, B b) in someList)` should not be seen as a cast.
+ if (AfterRParen->is(Keywords.kw_in) && Style.isCSharp())
+ return false;
+
+ // Functions which end with decorations like volatile, noexcept are unlikely
+ // to be casts.
+ if (AfterRParen->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
+ tok::kw_requires, tok::kw_throw, tok::arrow,
+ Keywords.kw_override, Keywords.kw_final) ||
+ isCppAttribute(IsCpp, *AfterRParen)) {
+ return false;
+ }
+
+ // As Java has no function types, a "(" after the ")" likely means that this
+ // is a cast.
+ if (Style.isJava() && AfterRParen->is(tok::l_paren))
+ return true;
+
+ // If a (non-string) literal follows, this is likely a cast.
+ if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
+ (AfterRParen->Tok.isLiteral() &&
+ AfterRParen->isNot(tok::string_literal))) {
+ return true;
+ }
+
+ auto IsNonVariableTemplate = [](const FormatToken &Tok) {
+ if (Tok.isNot(TT_TemplateCloser))
+ return false;
+ const auto *Less = Tok.MatchingParen;
+ if (!Less)
+ return false;
+ const auto *BeforeLess = Less->getPreviousNonComment();
+ return BeforeLess && BeforeLess->isNot(TT_VariableTemplate);
+ };
+
+ // Heuristically try to determine whether the parentheses contain a type.
+ auto IsQualifiedPointerOrReference = [](const FormatToken *T,
+ const LangOptions &LangOpts) {
+ // This is used to handle cases such as x = (foo *const)&y;
+ assert(!T->isTypeName(LangOpts) && "Should have already been checked");
+ // Strip trailing qualifiers such as const or volatile when checking
+ // whether the parens could be a cast to a pointer/reference type.
+ while (T) {
+ if (T->is(TT_AttributeRParen)) {
+ // Handle `x = (foo *__attribute__((foo)))&v;`:
+ assert(T->is(tok::r_paren));
+ assert(T->MatchingParen);
+ assert(T->MatchingParen->is(tok::l_paren));
+ assert(T->MatchingParen->is(TT_AttributeLParen));
+ if (const auto *Tok = T->MatchingParen->Previous;
+ Tok && Tok->isAttribute()) {
+ T = Tok->Previous;
+ continue;
+ }
+ } else if (T->is(TT_AttributeRSquare)) {
+ // Handle `x = (foo *[[clang::foo]])&v;`:
+ if (T->MatchingParen && T->MatchingParen->Previous) {
+ T = T->MatchingParen->Previous;
+ continue;
+ }
+ } else if (T->canBePointerOrReferenceQualifier()) {
+ T = T->Previous;
+ continue;
+ }
+ break;
+ }
+ return T && T->is(TT_PointerOrReference);
+ };
+
+ bool ParensAreType = IsNonVariableTemplate(*BeforeRParen) ||
+ BeforeRParen->is(TT_TypeDeclarationParen) ||
+ BeforeRParen->isTypeName(LangOpts) ||
+ IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
+ bool ParensCouldEndDecl =
+ AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
+ if (ParensAreType && !ParensCouldEndDecl)
+ return true;
+
+ // At this point, we heuristically assume that there are no casts at the
+ // start of the line. We assume that we have found most cases where there
+ // are by the logic above, e.g. "(void)x;".
+ if (!LeftOfParens)
+ return false;
+
+ // Certain token types inside the parentheses mean that this can't be a
+ // cast.
+ for (const auto *Token = LParen->Next; Token != &Tok; Token = Token->Next)
+ if (Token->is(TT_BinaryOperator))
+ return false;
+
+ // If the following token is an identifier or 'this', this is a cast. All
+ // cases where this can be something else are handled above.
+ if (AfterRParen->isOneOf(tok::identifier, tok::kw_this))
+ return true;
+
+ // Look for a cast `( x ) (`, where x may be a qualified identifier.
+ if (AfterRParen->is(tok::l_paren)) {
+ for (const auto *Prev = BeforeRParen; Prev->is(tok::identifier);) {
+ Prev = Prev->Previous;
+ if (Prev->is(tok::coloncolon))
+ Prev = Prev->Previous;
+ if (Prev == LParen)
+ return true;
+ }
+ }
+
+ if (!AfterRParen->Next)
+ return false;
+
+ // A pair of parentheses before an l_brace in C starts a compound literal
+ // and is not a cast.
+ if (Style.Language != FormatStyle::LK_C && AfterRParen->is(tok::l_brace) &&
+ AfterRParen->getBlockKind() == BK_BracedInit) {
+ return true;
+ }
+
+ // If the next token after the parenthesis is a unary operator, assume
+ // that this is cast, unless there are unexpected tokens inside the
+ // parenthesis.
+ const bool NextIsAmpOrStar = AfterRParen->isOneOf(tok::amp, tok::star);
+ if (!(AfterRParen->isUnaryOperator() || NextIsAmpOrStar) ||
+ AfterRParen->is(tok::plus) ||
+ AfterRParen->Next->isNoneOf(tok::identifier, tok::numeric_constant)) {
+ return false;
+ }
+
+ if (NextIsAmpOrStar &&
+ (AfterRParen->Next->is(tok::numeric_constant) || Line.InPPDirective)) {
+ return false;
+ }
+
+ if (Line.InPPDirective && AfterRParen->is(tok::minus))
+ return false;
+
+ const auto *Prev = BeforeRParen;
+
+ // Look for a function pointer type, e.g. `(*)()`.
+ if (Prev->is(tok::r_paren)) {
+ if (Prev->is(TT_CastRParen))
+ return false;
+ Prev = Prev->MatchingParen;
+ if (!Prev)
+ return false;
+ Prev = Prev->Previous;
+ if (!Prev || Prev->isNot(tok::r_paren))
+ return false;
+ Prev = Prev->MatchingParen;
+ return Prev && Prev->is(TT_FunctionTypeLParen);
+ }
+
+ // Search for unexpected tokens.
+ for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
+ if (Prev->isNoneOf(tok::kw_const, tok::identifier, tok::coloncolon))
+ return false;
+
+ return true;
+ }
+
+ /// Returns true if the token is used as a unary operator.
+ bool determineUnaryOperatorByUsage(const FormatToken &Tok) {
+ const FormatToken *PrevToken = Tok.getPreviousNonComment();
+ if (!PrevToken)
+ return true;
+
+ // These keywords are deliberately not included here because they may
+ // precede only one of unary star/amp and plus/minus but not both. They are
+ // either included in determineStarAmpUsage or determinePlusMinusCaretUsage.
+ //
+ // @ - It may be followed by a unary `-` in Objective-C literals. We don't
+ // know how they can be followed by a star or amp.
+ if (PrevToken->isOneOf(
+ TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi,
+ tok::equal, tok::question, tok::l_square, tok::l_brace,
+ tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield,
+ tok::kw_delete, tok::kw_return, tok::kw_throw)) {
+ return true;
+ }
+
+ // We put sizeof here instead of only in determineStarAmpUsage. In the cases
+ // where the unary `+` operator is overloaded, it is reasonable to write
+ // things like `sizeof +x`. Like commit 446d6ec996c6c3.
+ if (PrevToken->is(tok::kw_sizeof))
+ return true;
+
+ // A sequence of leading unary operators.
+ if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
+ return true;
+
+ // There can't be two consecutive binary operators.
+ if (PrevToken->is(TT_BinaryOperator))
+ return true;
+
+ return false;
+ }
+
+ /// Return the type of the given token assuming it is * or &.
+ TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
+ bool InTemplateArgument) {
+ if (Style.isJavaScript())
+ return TT_BinaryOperator;
+
+ // && in C# must be a binary operator.
+ if (Style.isCSharp() && Tok.is(tok::ampamp))
+ return TT_BinaryOperator;
+
+ if (Style.isVerilog()) {
+ // In Verilog, `*` can only be a binary operator. `&` can be either unary
+ // or binary. `*` also includes `*>` in module path declarations in
+ // specify blocks because merged tokens take the type of the first one by
+ // default.
+ if (Tok.is(tok::star))
+ return TT_BinaryOperator;
+ return determineUnaryOperatorByUsage(Tok) ? TT_UnaryOperator
+ : TT_BinaryOperator;
+ }
+
+ const FormatToken *PrevToken = Tok.getPreviousNonComment();
+ if (!PrevToken)
+ return TT_UnaryOperator;
+ if (PrevToken->isTypeName(LangOpts))
+ return TT_PointerOrReference;
+ if (PrevToken->isPlacementOperator() && Tok.is(tok::ampamp))
+ return TT_BinaryOperator;
+
+ auto *NextToken = Tok.getNextNonComment();
+ if (!NextToken)
+ return TT_PointerOrReference;
+ if (NextToken->is(tok::greater))
+ return TT_PointerOrReference;
+
+ if (InTemplateArgument && NextToken->is(tok::kw_noexcept))
+ return TT_BinaryOperator;
+
+ if (NextToken->isOneOf(tok::arrow, tok::equal, tok::comma, tok::r_paren,
+ tok::semi, TT_RequiresClause) ||
+ (NextToken->is(tok::kw_noexcept) && !IsExpression) ||
+ NextToken->canBePointerOrReferenceQualifier() ||
+ (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) {
+ return TT_PointerOrReference;
+ }
+
+ if (PrevToken->is(tok::coloncolon))
+ return TT_PointerOrReference;
+
+ if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
+ return TT_PointerOrReference;
+
+ if (determineUnaryOperatorByUsage(Tok))
+ return TT_UnaryOperator;
+
+ if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
+ return TT_PointerOrReference;
+ if (NextToken->is(tok::kw_operator) && !IsExpression)
+ return TT_PointerOrReference;
+
+ // After right braces, star tokens are likely to be pointers to struct,
+ // union, or class.
+ // struct {} *ptr;
+ // This by itself is not sufficient to distinguish from multiplication
+ // following a brace-initialized expression, as in:
+ // int i = int{42} * 2;
+ // In the struct case, the part of the struct declaration until the `{` and
+ // the `}` are put on separate unwrapped lines; in the brace-initialized
+ // case, the matching `{` is on the same unwrapped line, so check for the
+ // presence of the matching brace to distinguish between those.
+ if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
+ !PrevToken->MatchingParen) {
+ return TT_PointerOrReference;
+ }
+
+ if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
+ return TT_UnaryOperator;
+
+ if (PrevToken->Tok.isLiteral() ||
+ PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
+ tok::kw_false, tok::r_brace)) {
+ return TT_BinaryOperator;
+ }
+
+ const FormatToken *NextNonParen = NextToken;
+ while (NextNonParen && NextNonParen->is(tok::l_paren))
+ NextNonParen = NextNonParen->getNextNonComment();
+ if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
+ NextNonParen->isOneOf(tok::kw_true, tok::kw_false) ||
+ NextNonParen->isUnaryOperator())) {
+ return TT_BinaryOperator;
+ }
+
+ // If we know we're in a template argument, there are no named declarations.
+ // Thus, having an identifier on the right-hand side indicates a binary
+ // operator.
+ if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
+ return TT_BinaryOperator;
+
+ // "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
+ // unary "&".
+ if (Tok.is(tok::ampamp) &&
+ NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
+ return TT_BinaryOperator;
+ }
+
+ // This catches some cases where evaluation order is used as control flow:
+ // aaa && aaa->f();
+ // Or expressions like:
+ // width * height * length
+ if (NextToken->Tok.isAnyIdentifier()) {
+ auto *NextNextToken = NextToken->getNextNonComment();
+ if (NextNextToken) {
+ if (NextNextToken->is(tok::arrow))
+ return TT_BinaryOperator;
+ if (NextNextToken->isPointerOrReference() &&
+ !NextToken->isObjCLifetimeQualifier(Style)) {
+ NextNextToken->setFinalizedType(TT_BinaryOperator);
+ return TT_BinaryOperator;
+ }
+ }
+ }
+
+ // It is very unlikely that we are going to find a pointer or reference type
+ // definition on the RHS of an assignment.
+ if (IsExpression && !Contexts.back().CaretFound &&
+ Line.getFirstNonComment()->isNot(
+ TT_RequiresClauseInARequiresExpression)) {
+ return TT_BinaryOperator;
+ }
+
+ // Opeartors at class scope are likely pointer or reference members.
+ if (!Scopes.empty() && Scopes.back() == ST_Class)
+ return TT_PointerOrReference;
+
+ // Tokens that indicate member access or chained operator& use.
+ auto IsChainedOperatorAmpOrMember = [](const FormatToken *token) {
+ return !token || token->isOneOf(tok::amp, tok::period, tok::arrow,
+ tok::arrowstar, tok::periodstar);
+ };
+
+ // It's more likely that & represents operator& than an uninitialized
+ // reference.
+ if (Tok.is(tok::amp) && PrevToken->Tok.isAnyIdentifier() &&
+ IsChainedOperatorAmpOrMember(PrevToken->getPreviousNonComment()) &&
+ NextToken && NextToken->Tok.isAnyIdentifier()) {
+ if (auto NextNext = NextToken->getNextNonComment();
+ NextNext &&
+ (IsChainedOperatorAmpOrMember(NextNext) || NextNext->is(tok::semi))) {
+ return TT_BinaryOperator;
+ }
+ }
+
+ if (Line.Type == LT_SimpleRequirement ||
+ (!Scopes.empty() && Scopes.back() == ST_CompoundRequirement)) {
+ return TT_BinaryOperator;
+ }
+
+ return TT_PointerOrReference;
+ }
+
+ TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
+ if (determineUnaryOperatorByUsage(Tok))
+ return TT_UnaryOperator;
+
+ const FormatToken *PrevToken = Tok.getPreviousNonComment();
+ if (!PrevToken)
+ return TT_UnaryOperator;
+
+ if (PrevToken->is(tok::at))
+ return TT_UnaryOperator;
+
+ // Fall back to marking the token as binary operator.
+ return TT_BinaryOperator;
+ }
+
+ /// Determine whether ++/-- are pre- or post-increments/-decrements.
+ TokenType determineIncrementUsage(const FormatToken &Tok) {
+ const FormatToken *PrevToken = Tok.getPreviousNonComment();
+ if (!PrevToken || PrevToken->is(TT_CastRParen))
+ return TT_UnaryOperator;
+ if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
+ return TT_TrailingUnaryOperator;
+
+ return TT_UnaryOperator;
+ }
+
+ SmallVector<Context, 8> Contexts;
+
+ const FormatStyle &Style;
+ AnnotatedLine &Line;
+ FormatToken *CurrentToken;
+ bool AutoFound;
+ bool IsCpp;
+ LangOptions LangOpts;
+ const AdditionalKeywords &Keywords;
+
+ SmallVector<ScopeType> &Scopes;
+
+ // Set of "<" tokens that do not open a template parameter list. If parseAngle
+ // determines that a specific token can't be a template opener, it will make
+ // same decision irrespective of the decisions for tokens leading up to it.
+ // Store this information to prevent this from causing exponential runtime.
+ llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
+
+ int TemplateDeclarationDepth;
+};
+
+static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
+static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
+
+/// Parses binary expressions by inserting fake parenthesis based on
+/// operator precedence.
+class ExpressionParser {
+public:
+ ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
+ AnnotatedLine &Line)
+ : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
+
+ /// Parse expressions with the given operator precedence.
+ void parse(int Precedence = 0) {
+ // Skip 'return' and ObjC selector colons as they are not part of a binary
+ // expression.
+ while (Current && (Current->is(tok::kw_return) ||
+ (Current->is(tok::colon) &&
+ Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) {
+ next();
+ }
+
+ if (!Current || Precedence > PrecedenceArrowAndPeriod)
+ return;
+
+ // Conditional expressions need to be parsed separately for proper nesting.
+ if (Precedence == prec::Conditional) {
+ parseConditionalExpr();
+ return;
+ }
+
+ // Parse unary operators, which all have a higher precedence than binary
+ // operators.
+ if (Precedence == PrecedenceUnaryOperator) {
+ parseUnaryOperator();
+ return;
+ }
+
+ FormatToken *Start = Current;
+ FormatToken *LatestOperator = nullptr;
+ unsigned OperatorIndex = 0;
+ // The first name of the current type in a port list.
+ FormatToken *VerilogFirstOfType = nullptr;
+
+ while (Current) {
+ // In Verilog ports in a module header that don't have a type take the
+ // type of the previous one. For example,
+ // module a(output b,
+ // c,
+ // output d);
+ // In this case there need to be fake parentheses around b and c.
+ if (Style.isVerilog() && Precedence == prec::Comma) {
+ VerilogFirstOfType =
+ verilogGroupDecl(VerilogFirstOfType, LatestOperator);
+ }
+
+ // Consume operators with higher precedence.
+ parse(Precedence + 1);
+
+ int CurrentPrecedence = getCurrentPrecedence();
+ if (CurrentPrecedence > prec::Conditional &&
+ CurrentPrecedence < prec::PointerToMember) {
+ // When BreakBinaryOperations is globally OnePerLine (no per-operator
+ // rules), flatten all precedence levels so that every operator is
+ // treated equally for line-breaking purposes. With per-operator rules
+ // we must preserve natural precedence so that higher-precedence
+ // sub-expressions (e.g. `x << 8` inside a `|` chain) stay grouped;
+ // mustBreakBinaryOperation() handles the forced breaks instead.
+ if (Style.BreakBinaryOperations.PerOperator.empty() &&
+ Style.BreakBinaryOperations.Default ==
+ FormatStyle::BBO_OnePerLine) {
+ CurrentPrecedence = prec::Additive;
+ }
+ }
+
+ if (Precedence == CurrentPrecedence && Current &&
+ Current->is(TT_SelectorName)) {
+ if (LatestOperator)
+ addFakeParenthesis(Start, prec::Level(Precedence));
+ Start = Current;
+ }
+
+ if ((Style.isCSharp() || Style.isJavaScript() || Style.isJava()) &&
+ Precedence == prec::Additive && Current) {
+ // A string can be broken without parentheses around it when it is
+ // already in a sequence of strings joined by `+` signs.
+ FormatToken *Prev = Current->getPreviousNonComment();
+ if (Prev && Prev->is(tok::string_literal) &&
+ (Prev == Start || Prev->endsSequence(tok::string_literal, tok::plus,
+ TT_StringInConcatenation))) {
+ Prev->setType(TT_StringInConcatenation);
+ }
+ }
+
+ // At the end of the line or when an operator with lower precedence is
+ // found, insert fake parenthesis and return.
+ if (!Current ||
+ (Current->closesScope() &&
+ (Current->MatchingParen || Current->is(TT_TemplateString))) ||
+ (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
+ (CurrentPrecedence == prec::Conditional &&
+ Precedence == prec::Assignment && Current->is(tok::colon))) {
+ break;
+ }
+
+ // Consume scopes: (), [], <> and {}
+ // In addition to that we handle require clauses as scope, so that the
+ // constraints in that are correctly indented.
+ if (Current->opensScope() ||
+ Current->isOneOf(TT_RequiresClause,
+ TT_RequiresClauseInARequiresExpression)) {
+ // In fragment of a JavaScript template string can look like '}..${' and
+ // thus close a scope and open a new one at the same time.
+ while (Current && (!Current->closesScope() || Current->opensScope())) {
+ next();
+ parse();
+ }
+ next();
+ } else {
+ // Operator found.
+ if (CurrentPrecedence == Precedence) {
+ if (LatestOperator)
+ LatestOperator->NextOperator = Current;
+ LatestOperator = Current;
+ Current->OperatorIndex = OperatorIndex;
+ ++OperatorIndex;
+ }
+ next(/*SkipPastLeadingComments=*/Precedence > 0);
+ }
+ }
+
+ // Group variables of the same type.
+ if (Style.isVerilog() && Precedence == prec::Comma && VerilogFirstOfType)
+ addFakeParenthesis(VerilogFirstOfType, prec::Comma);
+
+ if (LatestOperator && (Current || Precedence > 0)) {
+ // The requires clauses do not neccessarily end in a semicolon or a brace,
+ // but just go over to struct/class or a function declaration, we need to
+ // intervene so that the fake right paren is inserted correctly.
+ auto End =
+ (Start->Previous &&
+ Start->Previous->isOneOf(TT_RequiresClause,
+ TT_RequiresClauseInARequiresExpression))
+ ? [this]() {
+ auto Ret = Current ? Current : Line.Last;
+ while (!Ret->ClosesRequiresClause && Ret->Previous)
+ Ret = Ret->Previous;
+ return Ret;
+ }()
+ : nullptr;
+
+ if (Precedence == PrecedenceArrowAndPeriod) {
+ // Call expressions don't have a binary operator precedence.
+ addFakeParenthesis(Start, prec::Unknown, End);
+ } else {
+ addFakeParenthesis(Start, prec::Level(Precedence), End);
+ }
+ }
+ }
+
+private:
+ /// Gets the precedence (+1) of the given token for binary operators
+ /// and other tokens that we treat like binary operators.
+ int getCurrentPrecedence() {
+ if (Current) {
+ const FormatToken *NextNonComment = Current->getNextNonComment();
+ if (Current->is(TT_ConditionalExpr))
+ return prec::Conditional;
+ if (NextNonComment && Current->is(TT_SelectorName) &&
+ (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
+ (Style.isProto() && NextNonComment->is(tok::less)))) {
+ return prec::Assignment;
+ }
+ if (Current->is(TT_JsComputedPropertyName))
+ return prec::Assignment;
+ if (Current->is(TT_LambdaArrow))
+ return prec::Comma;
+ if (Current->is(TT_FatArrow))
+ return prec::Assignment;
+ if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
+ (Current->is(tok::comment) && NextNonComment &&
+ NextNonComment->is(TT_SelectorName))) {
+ return 0;
+ }
+ if (Current->is(TT_RangeBasedForLoopColon))
+ return prec::Comma;
+ if ((Style.isJava() || Style.isJavaScript()) &&
+ Current->is(Keywords.kw_instanceof)) {
+ return prec::Relational;
+ }
+ if (Style.isJavaScript() &&
+ Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) {
+ return prec::Relational;
+ }
+ if (Current->isOneOf(TT_BinaryOperator, tok::comma))
+ return Current->getPrecedence();
+ if (Current->isOneOf(tok::period, tok::arrow) &&
+ Current->isNot(TT_TrailingReturnArrow)) {
+ return PrecedenceArrowAndPeriod;
+ }
+ if ((Style.isJava() || Style.isJavaScript()) &&
+ Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
+ Keywords.kw_throws)) {
+ return 0;
+ }
+ // In Verilog case labels are not on separate lines straight out of
+ // UnwrappedLineParser. The colon is not part of an expression.
+ if (Style.isVerilog() && Current->is(tok::colon))
+ return 0;
+ }
+ return -1;
+ }
+
+ void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
+ FormatToken *End = nullptr) {
+ // Do not assign fake parenthesis to tokens that are part of an
+ // unexpanded macro call. The line within the macro call contains
+ // the parenthesis and commas, and we will not find operators within
+ // that structure.
+ if (Start->MacroParent)
+ return;
+
+ Start->FakeLParens.push_back(Precedence);
+ if (Precedence > prec::Unknown)
+ Start->StartsBinaryExpression = true;
+ if (!End && Current)
+ End = Current->getPreviousNonComment();
+ if (End) {
+ ++End->FakeRParens;
+ if (Precedence > prec::Unknown)
+ End->EndsBinaryExpression = true;
+ }
+ }
+
+ /// Parse unary operator expressions and surround them with fake
+ /// parentheses if appropriate.
+ void parseUnaryOperator() {
+ SmallVector<FormatToken *, 2> Tokens;
+ while (Current && Current->is(TT_UnaryOperator)) {
+ Tokens.push_back(Current);
+ next();
+ }
+ parse(PrecedenceArrowAndPeriod);
+ for (FormatToken *Token : reverse(Tokens)) {
+ // The actual precedence doesn't matter.
+ addFakeParenthesis(Token, prec::Unknown);
+ }
+ }
+
+ void parseConditionalExpr() {
+ while (Current && Current->isTrailingComment())
+ next();
+ FormatToken *Start = Current;
+ parse(prec::LogicalOr);
+ if (!Current || Current->isNot(tok::question))
+ return;
+ next();
+ parse(prec::Assignment);
+ if (!Current || Current->isNot(TT_ConditionalExpr))
+ return;
+ next();
+ parse(prec::Assignment);
+ addFakeParenthesis(Start, prec::Conditional);
+ }
+
+ void next(bool SkipPastLeadingComments = true) {
+ if (Current)
+ Current = Current->Next;
+ while (Current &&
+ (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
+ Current->isTrailingComment()) {
+ Current = Current->Next;
+ }
+ }
+
+ // Add fake parenthesis around declarations of the same type for example in a
+ // module prototype. Return the first port / variable of the current type.
+ FormatToken *verilogGroupDecl(FormatToken *FirstOfType,
+ FormatToken *PreviousComma) {
+ if (!Current)
+ return nullptr;
+
+ FormatToken *Start = Current;
+
+ // Skip attributes.
+ while (Start->startsSequence(tok::l_paren, tok::star)) {
+ if (!(Start = Start->MatchingParen) ||
+ !(Start = Start->getNextNonComment())) {
+ return nullptr;
+ }
+ }
+
+ FormatToken *Tok = Start;
+
+ if (Tok->is(Keywords.kw_assign))
+ Tok = Tok->getNextNonComment();
+
+ // Skip any type qualifiers to find the first identifier. It may be either a
+ // new type name or a variable name. There can be several type qualifiers
+ // preceding a variable name, and we can not tell them apart by looking at
+ // the word alone since a macro can be defined as either a type qualifier or
+ // a variable name. Thus we use the last word before the dimensions instead
+ // of the first word as the candidate for the variable or type name.
+ FormatToken *First = nullptr;
+ while (Tok) {
+ FormatToken *Next = Tok->getNextNonComment();
+
+ if (Tok->is(tok::hash)) {
+ // Start of a macro expansion.
+ First = Tok;
+ Tok = Next;
+ if (Tok)
+ Tok = Tok->getNextNonComment();
+ } else if (Tok->is(tok::hashhash)) {
+ // Concatenation. Skip.
+ Tok = Next;
+ if (Tok)
+ Tok = Tok->getNextNonComment();
+ } else if (Keywords.isVerilogQualifier(*Tok) ||
+ Keywords.isVerilogIdentifier(*Tok)) {
+ First = Tok;
+ Tok = Next;
+ // The name may have dots like `interface_foo.modport_foo`.
+ while (Tok && Tok->isOneOf(tok::period, tok::coloncolon) &&
+ (Tok = Tok->getNextNonComment())) {
+ if (Keywords.isVerilogIdentifier(*Tok))
+ Tok = Tok->getNextNonComment();
+ }
+ } else if (!Next) {
+ Tok = nullptr;
+ } else if (Tok->is(tok::l_paren)) {
+ // Make sure the parenthesized list is a drive strength. Otherwise the
+ // statement may be a module instantiation in which case we have already
+ // found the instance name.
+ if (Next->isOneOf(
+ Keywords.kw_highz0, Keywords.kw_highz1, Keywords.kw_large,
+ Keywords.kw_medium, Keywords.kw_pull0, Keywords.kw_pull1,
+ Keywords.kw_small, Keywords.kw_strong0, Keywords.kw_strong1,
+ Keywords.kw_supply0, Keywords.kw_supply1, Keywords.kw_weak0,
+ Keywords.kw_weak1)) {
+ Tok->setType(TT_VerilogStrength);
+ Tok = Tok->MatchingParen;
+ if (Tok) {
+ Tok->setType(TT_VerilogStrength);
+ Tok = Tok->getNextNonComment();
+ }
+ } else {
+ break;
+ }
+ } else if (Tok->is(Keywords.kw_verilogHash)) {
+ // Delay control.
+ if (Next->is(tok::l_paren))
+ Next = Next->MatchingParen;
+ if (Next)
+ Tok = Next->getNextNonComment();
+ } else {
+ break;
+ }
+ }
+
+ // Find the second identifier. If it exists it will be the name.
+ FormatToken *Second = nullptr;
+ // Dimensions.
+ while (Tok && Tok->is(tok::l_square) && (Tok = Tok->MatchingParen))
+ Tok = Tok->getNextNonComment();
+ if (Tok && (Tok->is(tok::hash) || Keywords.isVerilogIdentifier(*Tok)))
+ Second = Tok;
+
+ // If the second identifier doesn't exist and there are qualifiers, the type
+ // is implied.
+ FormatToken *TypedName = nullptr;
+ if (Second) {
+ TypedName = Second;
+ if (First && First->is(TT_Unknown))
+ First->setType(TT_VerilogDimensionedTypeName);
+ } else if (First != Start) {
+ // If 'First' is null, then this isn't a declaration, 'TypedName' gets set
+ // to null as intended.
+ TypedName = First;
+ }
+
+ if (TypedName) {
+ // This is a declaration with a new type.
+ if (TypedName->is(TT_Unknown))
+ TypedName->setType(TT_StartOfName);
+ // Group variables of the previous type.
+ if (FirstOfType && PreviousComma) {
+ PreviousComma->setType(TT_VerilogTypeComma);
+ addFakeParenthesis(FirstOfType, prec::Comma, PreviousComma->Previous);
+ }
+
+ FirstOfType = TypedName;
+
+ // Don't let higher precedence handle the qualifiers. For example if we
+ // have:
+ // parameter x = 0
+ // We skip `parameter` here. This way the fake parentheses for the
+ // assignment will be around `x = 0`.
+ while (Current && Current != FirstOfType) {
+ if (Current->opensScope()) {
+ next();
+ parse();
+ }
+ next();
+ }
+ }
+
+ return FirstOfType;
+ }
+
+ const FormatStyle &Style;
+ const AdditionalKeywords &Keywords;
+ const AnnotatedLine &Line;
+ FormatToken *Current;
+};
+
+} // end anonymous namespace
+
+void TokenAnnotator::setCommentLineLevels(
+ SmallVectorImpl<AnnotatedLine *> &Lines) const {
+ const AnnotatedLine *NextNonCommentLine = nullptr;
+ for (AnnotatedLine *Line : reverse(Lines)) {
+ assert(Line->First);
+
+ // If the comment is currently aligned with the line immediately following
+ // it, that's probably intentional and we should keep it.
+ if (NextNonCommentLine && NextNonCommentLine->First->NewlinesBefore < 2 &&
+ Line->isComment() && !isClangFormatOff(Line->First->TokenText) &&
+ NextNonCommentLine->First->OriginalColumn ==
+ Line->First->OriginalColumn) {
+ const bool PPDirectiveOrImportStmt =
+ NextNonCommentLine->Type == LT_PreprocessorDirective ||
+ NextNonCommentLine->Type == LT_ImportStatement;
+ if (PPDirectiveOrImportStmt)
+ Line->Type = LT_CommentAbovePPDirective;
+ // Align comments for preprocessor lines with the # in column 0 if
+ // preprocessor lines are not indented. Otherwise, align with the next
+ // line.
+ Line->Level = Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
+ PPDirectiveOrImportStmt
+ ? 0
+ : NextNonCommentLine->Level;
+ } else {
+ NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
+ }
+
+ setCommentLineLevels(Line->Children);
+ }
+}
+
+static unsigned maxNestingDepth(const AnnotatedLine &Line) {
+ unsigned Result = 0;
+ for (const auto *Tok = Line.First; Tok; Tok = Tok->Next)
+ Result = std::max(Result, Tok->NestingLevel);
+ return Result;
+}
+
+// Returns the token after the first qualifier of the name, or nullptr if there
+// is no qualifier.
+static FormatToken *skipNameQualifier(const FormatToken *Tok) {
+ assert(Tok);
+
+ // Qualified names must start with an identifier.
+ if (Tok->isNot(tok::identifier))
+ return nullptr;
+
+ Tok = Tok->getNextNonComment();
+ if (!Tok)
+ return nullptr;
+
+ // Consider: A::B::B()
+ // Tok --^
+ if (Tok->is(tok::coloncolon))
+ return Tok->getNextNonComment();
+
+ // Consider: A<float>::B<int>::B()
+ // Tok --^
+ if (Tok->is(TT_TemplateOpener)) {
+ Tok = Tok->MatchingParen;
+ if (!Tok)
+ return nullptr;
+
+ Tok = Tok->getNextNonComment();
+ if (!Tok)
+ return nullptr;
+ }
+
+ return Tok->is(tok::coloncolon) ? Tok->getNextNonComment() : nullptr;
+}
+
+// Returns the name of a function with no return type, e.g. a constructor or
+// destructor.
+static FormatToken *getFunctionName(const AnnotatedLine &Line,
+ FormatToken *&OpeningParen) {
+ for (FormatToken *Tok = Line.getFirstNonComment(), *Name = nullptr; Tok;
+ Tok = Tok->getNextNonComment()) {
+ // Skip C++11 attributes both before and after the function name.
+ if (Tok->is(TT_AttributeLSquare)) {
+ Tok = Tok->MatchingParen;
+ if (!Tok)
+ return nullptr;
+ continue;
+ }
+
+ // Make sure the name is followed by a pair of parentheses.
+ if (Name) {
+ if (Tok->is(tok::l_paren) && Tok->is(TT_Unknown) && Tok->MatchingParen) {
+ OpeningParen = Tok;
+ return Name;
+ }
+ return nullptr;
+ }
+
+ // Skip keywords that may precede the constructor/destructor name.
+ if (Tok->isOneOf(tok::kw_friend, tok::kw_inline, tok::kw_virtual,
+ tok::kw_constexpr, tok::kw_consteval, tok::kw_explicit)) {
+ continue;
+ }
+
+ // Skip past template typename declarations that may precede the
+ // constructor/destructor name.
+ if (Tok->is(tok::kw_template)) {
+ Tok = Tok->getNextNonComment();
+ if (!Tok)
+ return nullptr;
+
+ // If the next token after the template keyword is not an opening bracket,
+ // it is a template instantiation, and not a function.
+ if (Tok->isNot(TT_TemplateOpener))
+ return nullptr;
+
+ Tok = Tok->MatchingParen;
+ if (!Tok)
+ return nullptr;
+
+ continue;
+ }
+
+ // A qualified name may start from the global namespace.
+ if (Tok->is(tok::coloncolon)) {
+ Tok = Tok->Next;
+ if (!Tok)
+ return nullptr;
+ }
+
+ // Skip to the unqualified part of the name.
+ while (auto *Next = skipNameQualifier(Tok))
+ Tok = Next;
+
+ // Skip the `~` if a destructor name.
+ if (Tok->is(tok::tilde)) {
+ Tok = Tok->Next;
+ if (!Tok)
+ return nullptr;
+ }
+
+ // Make sure the name is not already annotated, e.g. as NamespaceMacro.
+ if (Tok->isNot(tok::identifier) || Tok->isNot(TT_Unknown))
+ return nullptr;
+
+ Name = Tok;
+ }
+
+ return nullptr;
+}
+
+// Checks if Tok is a constructor/destructor name qualified by its class name.
+static bool isCtorOrDtorName(const FormatToken *Tok) {
+ assert(Tok && Tok->is(tok::identifier));
+ const auto *Prev = Tok->Previous;
+
+ if (Prev && Prev->is(tok::tilde))
+ Prev = Prev->Previous;
+
+ // Consider: A::A() and A<int>::A()
+ if (!Prev || (!Prev->endsSequence(tok::coloncolon, tok::identifier) &&
+ !Prev->endsSequence(tok::coloncolon, TT_TemplateCloser))) {
+ return false;
+ }
+
+ assert(Prev->Previous);
+ if (Prev->Previous->is(TT_TemplateCloser) && Prev->Previous->MatchingParen) {
+ Prev = Prev->Previous->MatchingParen;
+ assert(Prev->Previous);
+ }
+
+ return Prev->Previous->TokenText == Tok->TokenText;
+}
+
+void TokenAnnotator::annotate(AnnotatedLine &Line) {
+ if (!Line.InMacroBody)
+ MacroBodyScopes.clear();
+
+ auto &ScopeStack = Line.InMacroBody ? MacroBodyScopes : Scopes;
+ AnnotatingParser Parser(Style, Line, Keywords, ScopeStack);
+ Line.Type = Parser.parseLine();
+
+ if (!Line.Children.empty()) {
+ ScopeStack.push_back(ST_Other);
+ const bool InRequiresExpression = Line.Type == LT_RequiresExpression;
+ for (auto &Child : Line.Children) {
+ if (InRequiresExpression &&
+ Child->First->isNoneOf(tok::kw_typename, tok::kw_requires,
+ TT_CompoundRequirementLBrace)) {
+ Child->Type = LT_SimpleRequirement;
+ }
+ annotate(*Child);
+ }
+ // ScopeStack can become empty if Child has an unmatched `}`.
+ if (!ScopeStack.empty())
+ ScopeStack.pop_back();
+ }
+
+ // With very deep nesting, ExpressionParser uses lots of stack and the
+ // formatting algorithm is very slow. We're not going to do a good job here
+ // anyway - it's probably generated code being formatted by mistake.
+ // Just skip the whole line.
+ if (maxNestingDepth(Line) > 50)
+ Line.Type = LT_Invalid;
+
+ if (Line.Type == LT_Invalid)
+ return;
+
+ ExpressionParser ExprParser(Style, Keywords, Line);
+ ExprParser.parse();
+
+ if (IsCpp) {
+ FormatToken *OpeningParen = nullptr;
+ auto *Tok = getFunctionName(Line, OpeningParen);
+ if (Tok && ((!ScopeStack.empty() && ScopeStack.back() == ST_Class) ||
+ Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
+ Tok->setFinalizedType(TT_CtorDtorDeclName);
+ assert(OpeningParen);
+ OpeningParen->setFinalizedType(TT_FunctionDeclarationLParen);
+ }
+ }
+
+ if (Line.startsWith(TT_ObjCMethodSpecifier))
+ Line.Type = LT_ObjCMethodDecl;
+ else if (Line.startsWith(TT_ObjCDecl))
+ Line.Type = LT_ObjCDecl;
+ else if (Line.startsWith(TT_ObjCProperty))
+ Line.Type = LT_ObjCProperty;
+
+ auto *First = Line.First;
+ First->SpacesRequiredBefore = 1;
+ First->CanBreakBefore = First->MustBreakBefore;
+}
+
+// This function heuristically determines whether 'Current' starts the name of a
+// function declaration.
+static bool isFunctionDeclarationName(const LangOptions &LangOpts,
+ const FormatToken &Current,
+ const AnnotatedLine &Line,
+ FormatToken *&ClosingParen) {
+ if (Current.is(TT_FunctionDeclarationName))
+ return true;
+
+ if (Current.isNoneOf(tok::identifier, tok::kw_operator))
+ return false;
+
+ const auto *Prev = Current.getPreviousNonComment();
+ assert(Prev);
+
+ const auto &Previous = *Prev;
+
+ if (const auto *PrevPrev = Previous.getPreviousNonComment();
+ PrevPrev && PrevPrev->is(TT_ObjCDecl)) {
+ return false;
+ }
+
+ auto skipOperatorName =
+ [&LangOpts](const FormatToken *Next) -> const FormatToken * {
+ for (; Next; Next = Next->Next) {
+ if (Next->is(TT_OverloadedOperatorLParen))
+ return Next;
+ if (Next->is(TT_OverloadedOperator))
+ continue;
+ if (Next->isPlacementOperator() || Next->is(tok::kw_co_await)) {
+ // For 'new[]' and 'delete[]'.
+ if (Next->Next &&
+ Next->Next->startsSequence(tok::l_square, tok::r_square)) {
+ Next = Next->Next->Next;
+ }
+ continue;
+ }
+ if (Next->startsSequence(tok::l_square, tok::r_square)) {
+ // For operator[]().
+ Next = Next->Next;
+ continue;
+ }
+ if ((Next->isTypeName(LangOpts) || Next->is(tok::identifier)) &&
+ Next->Next && Next->Next->isPointerOrReference()) {
+ // For operator void*(), operator char*(), operator Foo*().
+ Next = Next->Next;
+ continue;
+ }
+ if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
+ Next = Next->MatchingParen;
+ continue;
+ }
+
+ break;
+ }
+ return nullptr;
+ };
+
+ const auto *Next = Current.Next;
+ const bool IsCpp = LangOpts.CXXOperatorNames || LangOpts.C11;
+
+ // Find parentheses of parameter list.
+ if (Current.is(tok::kw_operator)) {
+ if (Line.startsWith(tok::kw_friend))
+ return true;
+ if (Previous.Tok.getIdentifierInfo() &&
+ Previous.isNoneOf(tok::kw_return, tok::kw_co_return)) {
+ return true;
+ }
+ if (Previous.is(tok::r_paren) && Previous.is(TT_TypeDeclarationParen)) {
+ assert(Previous.MatchingParen);
+ assert(Previous.MatchingParen->is(tok::l_paren));
+ assert(Previous.MatchingParen->is(TT_TypeDeclarationParen));
+ return true;
+ }
+ if (!Previous.isPointerOrReference() && Previous.isNot(TT_TemplateCloser))
+ return false;
+ Next = skipOperatorName(Next);
+ } else {
+ if (Current.isNot(TT_StartOfName) || Current.NestingLevel != 0)
+ return false;
+ while (Next && Next->startsSequence(tok::hashhash, tok::identifier))
+ Next = Next->Next->Next;
+ for (; Next; Next = Next->Next) {
+ if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
+ Next = Next->MatchingParen;
+ } else if (Next->is(tok::coloncolon)) {
+ Next = Next->Next;
+ if (!Next)
+ return false;
+ if (Next->is(tok::kw_operator)) {
+ Next = skipOperatorName(Next->Next);
+ break;
+ }
+ if (Next->isNot(tok::identifier))
+ return false;
+ } else if (isCppAttribute(IsCpp, *Next)) {
+ Next = Next->MatchingParen;
+ if (!Next)
+ return false;
+ } else if (Next->is(tok::l_paren)) {
+ break;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ // Check whether parameter list can belong to a function declaration.
+ if (!Next || Next->isNot(tok::l_paren) || !Next->MatchingParen)
+ return false;
+ ClosingParen = Next->MatchingParen;
+ assert(ClosingParen->is(tok::r_paren));
+ // If the lines ends with "{", this is likely a function definition.
+ if (Line.Last->is(tok::l_brace))
+ return true;
+ if (Next->Next == ClosingParen)
+ return true; // Empty parentheses.
+ // If there is an &/&& after the r_paren, this is likely a function.
+ if (ClosingParen->Next && ClosingParen->Next->is(TT_PointerOrReference))
+ return true;
+
+ // Check for K&R C function definitions (and C++ function definitions with
+ // unnamed parameters), e.g.:
+ // int f(i)
+ // {
+ // return i + 1;
+ // }
+ // bool g(size_t = 0, bool b = false)
+ // {
+ // return !b;
+ // }
+ if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
+ !Line.endsWith(tok::semi)) {
+ return true;
+ }
+
+ for (const FormatToken *Tok = Next->Next; Tok && Tok != ClosingParen;
+ Tok = Tok->Next) {
+ if (Tok->is(TT_TypeDeclarationParen))
+ return true;
+ if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
+ Tok = Tok->MatchingParen;
+ continue;
+ }
+ if (Tok->is(tok::kw_const) || Tok->isTypeName(LangOpts) ||
+ Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
+ return true;
+ }
+ if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
+ return false;
+ }
+ return false;
+}
+
+bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
+ assert(Line.MightBeFunctionDecl);
+
+ if ((Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
+ Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevelDefinitions) &&
+ Line.Level > 0) {
+ return false;
+ }
+
+ switch (Style.BreakAfterReturnType) {
+ case FormatStyle::RTBS_None:
+ case FormatStyle::RTBS_Automatic:
+ case FormatStyle::RTBS_ExceptShortType:
+ return false;
+ case FormatStyle::RTBS_All:
+ case FormatStyle::RTBS_TopLevel:
+ return true;
+ case FormatStyle::RTBS_AllDefinitions:
+ case FormatStyle::RTBS_TopLevelDefinitions:
+ return Line.mightBeFunctionDefinition();
+ }
+
+ return false;
+}
+
+void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
+ if (Line.Computed)
+ return;
+
+ Line.Computed = true;
+
+ for (AnnotatedLine *ChildLine : Line.Children)
+ calculateFormattingInformation(*ChildLine);
+
+ auto *First = Line.First;
+ First->TotalLength = First->IsMultiline
+ ? Style.ColumnLimit
+ : Line.FirstStartColumn + First->ColumnWidth;
+ bool AlignArrayOfStructures =
+ (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
+ Line.Type == LT_ArrayOfStructInitializer);
+ if (AlignArrayOfStructures)
+ calculateArrayInitializerColumnList(Line);
+
+ const auto *FirstNonComment = Line.getFirstNonComment();
+ bool SeenName = false;
+ bool LineIsFunctionDeclaration = false;
+ FormatToken *AfterLastAttribute = nullptr;
+ FormatToken *ClosingParen = nullptr;
+
+ for (auto *Tok = FirstNonComment && FirstNonComment->isNot(tok::kw_using)
+ ? FirstNonComment->Next
+ : nullptr;
+ Tok && Tok->isNot(BK_BracedInit); Tok = Tok->Next) {
+ if (Tok->is(TT_StartOfName))
+ SeenName = true;
+ if (Tok->Previous->EndsCppAttributeGroup)
+ AfterLastAttribute = Tok;
+ if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
+ IsCtorOrDtor ||
+ isFunctionDeclarationName(LangOpts, *Tok, Line, ClosingParen)) {
+ if (!IsCtorOrDtor)
+ Tok->setFinalizedType(TT_FunctionDeclarationName);
+ LineIsFunctionDeclaration = true;
+ SeenName = true;
+ if (ClosingParen) {
+ auto *OpeningParen = ClosingParen->MatchingParen;
+ assert(OpeningParen);
+ if (OpeningParen->is(TT_Unknown))
+ OpeningParen->setType(TT_FunctionDeclarationLParen);
+ }
+ break;
+ }
+ }
+
+ if (IsCpp) {
+ if ((LineIsFunctionDeclaration ||
+ (FirstNonComment && FirstNonComment->is(TT_CtorDtorDeclName))) &&
+ Line.endsWith(tok::semi, tok::r_brace)) {
+ auto *Tok = Line.Last->Previous;
+ while (Tok->isNot(tok::r_brace))
+ Tok = Tok->Previous;
+ if (auto *LBrace = Tok->MatchingParen; LBrace && LBrace->is(TT_Unknown)) {
+ assert(LBrace->is(tok::l_brace));
+ Tok->setBlockKind(BK_Block);
+ LBrace->setBlockKind(BK_Block);
+ LBrace->setFinalizedType(TT_FunctionLBrace);
+ }
+ }
+
+ if (SeenName && AfterLastAttribute &&
+ mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
+ AfterLastAttribute->MustBreakBefore = true;
+ if (LineIsFunctionDeclaration)
+ Line.ReturnTypeWrapped = true;
+ }
+
+ if (!LineIsFunctionDeclaration) {
+ Line.ReturnTypeWrapped = false;
+ // Annotate */&/&& in `operator` function calls as binary operators.
+ for (const auto *Tok = FirstNonComment; Tok; Tok = Tok->Next) {
+ if (Tok->isNot(tok::kw_operator))
+ continue;
+ do {
+ Tok = Tok->Next;
+ } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
+ if (!Tok || !Tok->MatchingParen)
+ break;
+ const auto *LeftParen = Tok;
+ for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
+ Tok = Tok->Next) {
+ if (Tok->isNot(tok::identifier))
+ continue;
+ auto *Next = Tok->Next;
+ const bool NextIsBinaryOperator =
+ Next && Next->isPointerOrReference() && Next->Next &&
+ Next->Next->is(tok::identifier);
+ if (!NextIsBinaryOperator)
+ continue;
+ Next->setType(TT_BinaryOperator);
+ Tok = Next;
+ }
+ }
+ } else if (ClosingParen) {
+ for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) {
+ if (Tok->is(TT_CtorInitializerColon))
+ break;
+ if (Tok->is(tok::arrow)) {
+ Tok->overwriteFixedType(TT_TrailingReturnArrow);
+ break;
+ }
+ if (Tok->isNot(TT_TrailingAnnotation))
+ continue;
+ const auto *Next = Tok->Next;
+ if (!Next || Next->isNot(tok::l_paren))
+ continue;
+ Tok = Next->MatchingParen;
+ if (!Tok)
+ break;
+ }
+ }
+ }
+
+ if (First->is(TT_ElseLBrace)) {
+ First->CanBreakBefore = true;
+ First->MustBreakBefore = true;
+ }
+
+ bool InFunctionDecl = Line.MightBeFunctionDecl;
+ bool InParameterList = false;
+ for (auto *Current = First->Next; Current; Current = Current->Next) {
+ const FormatToken *Prev = Current->Previous;
+ if (Current->is(TT_LineComment)) {
+ if (Prev->is(BK_BracedInit) && Prev->opensScope()) {
+ Current->SpacesRequiredBefore =
+ (Style.Cpp11BracedListStyle == FormatStyle::BLS_AlignFirstComment &&
+ !Style.SpacesInParensOptions.Other)
+ ? 0
+ : 1;
+ } else if (Prev->is(TT_VerilogMultiLineListLParen)) {
+ Current->SpacesRequiredBefore = 0;
+ } else {
+ Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
+ }
+
+ // If we find a trailing comment, iterate backwards to determine whether
+ // it seems to relate to a specific parameter. If so, break before that
+ // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
+ // to the previous line in:
+ // SomeFunction(a,
+ // b, // comment
+ // c);
+ if (!Current->HasUnescapedNewline) {
+ for (FormatToken *Parameter = Current->Previous; Parameter;
+ Parameter = Parameter->Previous) {
+ if (Parameter->isOneOf(tok::comment, tok::r_brace))
+ break;
+ if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
+ if (Parameter->Previous->isNot(TT_CtorInitializerComma) &&
+ Parameter->HasUnescapedNewline) {
+ Parameter->MustBreakBefore = true;
+ }
+ break;
+ }
+ }
+ }
+ } else if (!Current->Finalized && Current->SpacesRequiredBefore == 0 &&
+ spaceRequiredBefore(Line, *Current)) {
+ Current->SpacesRequiredBefore = 1;
+ }
+
+ const auto &Children = Prev->Children;
+ if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
+ Current->MustBreakBefore = true;
+ } else {
+ Current->MustBreakBefore =
+ Current->MustBreakBefore || mustBreakBefore(Line, *Current);
+ if (!Current->MustBreakBefore && InFunctionDecl &&
+ Current->is(TT_FunctionDeclarationName)) {
+ Current->MustBreakBefore = mustBreakForReturnType(Line);
+ }
+ }
+
+ Current->CanBreakBefore =
+ Current->MustBreakBefore || canBreakBefore(Line, *Current);
+
+ if (Current->is(TT_FunctionDeclarationLParen)) {
+ InParameterList = true;
+ } else if (Current->is(tok::r_paren)) {
+ const auto *LParen = Current->MatchingParen;
+ if (LParen && LParen->is(TT_FunctionDeclarationLParen))
+ InParameterList = false;
+ } else if (InParameterList &&
+ Current->endsSequence(TT_AttributeMacro,
+ TT_PointerOrReference)) {
+ Current->CanBreakBefore = false;
+ }
+
+ unsigned ChildSize = 0;
+ if (Prev->Children.size() == 1) {
+ FormatToken &LastOfChild = *Prev->Children[0]->Last;
+ ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
+ : LastOfChild.TotalLength + 1;
+ }
+ if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
+ (Prev->Children.size() == 1 &&
+ Prev->Children[0]->First->MustBreakBefore) ||
+ Current->IsMultiline) {
+ Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
+ } else {
+ Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
+ ChildSize + Current->SpacesRequiredBefore;
+ }
+
+ if (Current->is(TT_ControlStatementLBrace)) {
+ if (Style.ColumnLimit > 0 &&
+ Style.BraceWrapping.AfterControlStatement ==
+ FormatStyle::BWACS_MultiLine &&
+ Line.Level * Style.IndentWidth + Line.Last->TotalLength >
+ Style.ColumnLimit) {
+ Current->CanBreakBefore = true;
+ Current->MustBreakBefore = true;
+ }
+ } else if (Current->is(TT_CtorInitializerColon)) {
+ InFunctionDecl = false;
+ }
+
+ // FIXME: Only calculate this if CanBreakBefore is true once static
+ // initializers etc. are sorted out.
+ // FIXME: Move magic numbers to a better place.
+
+ // Reduce penalty for aligning ObjC method arguments using the colon
+ // alignment as this is the canonical way (still prefer fitting everything
+ // into one line if possible). Trying to fit a whole expression into one
+ // line should not force other line breaks (e.g. when ObjC method
+ // expression is a part of other expression).
+ Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
+ if (Style.Language == FormatStyle::LK_ObjC &&
+ Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
+ if (Current->ParameterIndex == 1)
+ Current->SplitPenalty += 5 * Current->BindingStrength;
+ } else {
+ Current->SplitPenalty += 20 * Current->BindingStrength;
+ }
+ }
+
+ calculateUnbreakableTailLengths(Line);
+ unsigned IndentLevel = Line.Level;
+ for (auto *Current = First; Current; Current = Current->Next) {
+ if (Current->Role)
+ Current->Role->precomputeFormattingInfos(Current);
+ if (Current->MatchingParen &&
+ Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
+ IndentLevel > 0) {
+ --IndentLevel;
+ }
+ Current->IndentLevel = IndentLevel;
+ if (Current->opensBlockOrBlockTypeList(Style))
+ ++IndentLevel;
+ }
+
+ LLVM_DEBUG({ printDebugInfo(Line); });
+}
+
+void TokenAnnotator::calculateUnbreakableTailLengths(
+ AnnotatedLine &Line) const {
+ unsigned UnbreakableTailLength = 0;
+ FormatToken *Current = Line.Last;
+ while (Current) {
+ Current->UnbreakableTailLength = UnbreakableTailLength;
+ if (Current->CanBreakBefore ||
+ Current->isOneOf(tok::comment, tok::string_literal)) {
+ UnbreakableTailLength = 0;
+ } else {
+ UnbreakableTailLength +=
+ Current->ColumnWidth + Current->SpacesRequiredBefore;
+ }
+ Current = Current->Previous;
+ }
+}
+
+void TokenAnnotator::calculateArrayInitializerColumnList(
+ AnnotatedLine &Line) const {
+ if (Line.First == Line.Last)
+ return;
+ auto *CurrentToken = Line.First;
+ CurrentToken->ArrayInitializerLineStart = true;
+ unsigned Depth = 0;
+ while (CurrentToken && CurrentToken != Line.Last) {
+ if (CurrentToken->is(tok::l_brace)) {
+ CurrentToken->IsArrayInitializer = true;
+ if (CurrentToken->Next)
+ CurrentToken->Next->MustBreakBefore = true;
+ CurrentToken =
+ calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
+ } else {
+ CurrentToken = CurrentToken->Next;
+ }
+ }
+}
+
+FormatToken *TokenAnnotator::calculateInitializerColumnList(
+ AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
+ while (CurrentToken && CurrentToken != Line.Last) {
+ if (CurrentToken->is(tok::l_brace))
+ ++Depth;
+ else if (CurrentToken->is(tok::r_brace))
+ --Depth;
+ if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
+ CurrentToken = CurrentToken->Next;
+ if (!CurrentToken)
+ break;
+ CurrentToken->StartsColumn = true;
+ CurrentToken = CurrentToken->Previous;
+ }
+ CurrentToken = CurrentToken->Next;
+ }
+ return CurrentToken;
+}
+
+unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
+ const FormatToken &Tok,
+ bool InFunctionDecl) const {
+ const FormatToken &Left = *Tok.Previous;
+ const FormatToken &Right = Tok;
+
+ if (Left.is(tok::semi))
+ return 0;
+
+ // Language specific handling.
+ if (Style.isJava()) {
+ if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
+ return 1;
+ if (Right.is(Keywords.kw_implements))
+ return 2;
+ if (Left.is(tok::comma) && Left.NestingLevel == 0)
+ return 3;
+ } else if (Style.isJavaScript()) {
+ if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
+ return 100;
+ if (Left.is(TT_JsTypeColon))
+ return 35;
+ if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
+ (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
+ return 100;
+ }
+ // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
+ if (Left.opensScope() && Right.closesScope())
+ return 200;
+ } else if (Style.Language == FormatStyle::LK_Proto) {
+ if (Right.is(tok::l_square))
+ return 1;
+ if (Right.is(tok::period))
+ return 500;
+ }
+
+ if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
+ return 1;
+ if (Right.is(tok::l_square)) {
+ if (Left.is(tok::r_square))
+ return 200;
+ // Slightly prefer formatting local lambda definitions like functions.
+ if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
+ return 35;
+ if (Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
+ TT_ArrayInitializerLSquare,
+ TT_DesignatedInitializerLSquare, TT_AttributeLSquare)) {
+ return 500;
+ }
+ }
+
+ if (Left.is(tok::coloncolon))
+ return Style.PenaltyBreakScopeResolution;
+ if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
+ tok::kw_operator)) {
+ if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
+ return 3;
+ if (Left.is(TT_StartOfName))
+ return 110;
+ if (InFunctionDecl && Right.NestingLevel == 0)
+ return Style.PenaltyReturnTypeOnItsOwnLine;
+ return 200;
+ }
+ if (Right.is(TT_PointerOrReference))
+ return 190;
+ if (Right.is(TT_LambdaArrow))
+ return 110;
+ if (Left.is(tok::equal) && Right.is(tok::l_brace))
+ return 160;
+ if (Left.is(TT_CastRParen))
+ return 100;
+ if (Left.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
+ return 5000;
+ if (Left.is(tok::comment))
+ return 1000;
+
+ if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
+ TT_CtorInitializerColon)) {
+ return 2;
+ }
+
+ if (Right.isMemberAccess()) {
+ // Breaking before the "./->" of a chained call/member access is reasonably
+ // cheap, as formatting those with one call per line is generally
+ // desirable. In particular, it should be cheaper to break before the call
+ // than it is to break inside a call's parameters, which could lead to weird
+ // "hanging" indents. The exception is the very last "./->" to support this
+ // frequent pattern:
+ //
+ // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
+ // dddddddd);
+ //
+ // which might otherwise be blown up onto many lines. Here, clang-format
+ // won't produce "hanging" indents anyway as there is no other trailing
+ // call.
+ //
+ // Also apply higher penalty is not a call as that might lead to a wrapping
+ // like:
+ //
+ // aaaaaaa
+ // .aaaaaaaaa.bbbbbbbb(cccccccc);
+ const auto *NextOperator = Right.NextOperator;
+ const auto Penalty = Style.PenaltyBreakBeforeMemberAccess;
+ return NextOperator && NextOperator->Previous->closesScope()
+ ? std::min(Penalty, 35u)
+ : Penalty;
+ }
+
+ if (Right.is(TT_TrailingAnnotation) &&
+ (!Right.Next || Right.Next->isNot(tok::l_paren))) {
+ // Moving trailing annotations to the next line is fine for ObjC method
+ // declarations.
+ if (Line.startsWith(TT_ObjCMethodSpecifier))
+ return 10;
+ // Generally, breaking before a trailing annotation is bad unless it is
+ // function-like. It seems to be especially preferable to keep standard
+ // annotations (i.e. "const", "final" and "override") on the same line.
+ // Use a slightly higher penalty after ")" so that annotations like
+ // "const override" are kept together.
+ bool is_short_annotation = Right.TokenText.size() < 10;
+ return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
+ }
+
+ // In for-loops, prefer breaking at ',' and ';'.
+ if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
+ return 4;
+
+ // In Objective-C method expressions, prefer breaking before "param:" over
+ // breaking after it.
+ if (Right.is(TT_SelectorName))
+ return 0;
+ if (Left.is(tok::colon)) {
+ if (Left.is(TT_ObjCMethodExpr))
+ return Line.MightBeFunctionDecl ? 50 : 500;
+ if (Left.is(TT_ObjCSelector))
+ return 500;
+ }
+
+ // In Objective-C type declarations, avoid breaking after the category's
+ // open paren (we'll prefer breaking after the protocol list's opening
+ // angle bracket, if present).
+ if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
+ Left.Previous->isOneOf(tok::identifier, tok::greater)) {
+ return 500;
+ }
+
+ if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
+ return Style.PenaltyBreakOpenParenthesis;
+ if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
+ return 100;
+ if (Left.is(tok::l_paren) && Left.Previous &&
+ (Left.Previous->isOneOf(tok::kw_for, tok::kw__Generic) ||
+ Left.Previous->isIf())) {
+ return 1000;
+ }
+ if (Left.is(tok::equal) && InFunctionDecl)
+ return 110;
+ if (Right.is(tok::r_brace))
+ return 1;
+ if (Left.is(TT_TemplateOpener))
+ return 100;
+ if (Left.opensScope()) {
+ // If we aren't aligning after opening parens/braces we can always break
+ // here unless the style does not want us to place all arguments on the
+ // next line.
+ if (!Style.AlignAfterOpenBracket &&
+ (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) {
+ return 0;
+ }
+ if (Left.is(tok::l_brace) &&
+ Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
+ return 19;
+ }
+ return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
+ : 19;
+ }
+ if (Left.is(TT_JavaAnnotation))
+ return 50;
+
+ if (Left.is(TT_UnaryOperator))
+ return 60;
+ if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
+ Left.Previous->isLabelString() &&
+ (Left.NextOperator || Left.OperatorIndex != 0)) {
+ return 50;
+ }
+ if (Right.is(tok::plus) && Left.isLabelString() &&
+ (Right.NextOperator || Right.OperatorIndex != 0)) {
+ return 25;
+ }
+ if (Left.is(tok::comma))
+ return 1;
+ if (Right.is(tok::lessless) && Left.isLabelString() &&
+ (Right.NextOperator || Right.OperatorIndex != 1)) {
+ return 25;
+ }
+ if (Right.is(tok::lessless)) {
+ // Breaking at a << is really cheap.
+ if (Left.isNot(tok::r_paren) || Right.OperatorIndex > 0) {
+ // Slightly prefer to break before the first one in log-like statements.
+ return 2;
+ }
+ return 1;
+ }
+ if (Left.ClosesTemplateDeclaration)
+ return Style.PenaltyBreakTemplateDeclaration;
+ if (Left.ClosesRequiresClause)
+ return 0;
+ if (Left.is(TT_ConditionalExpr))
+ return prec::Conditional;
+ prec::Level Level = Left.getPrecedence();
+ if (Level == prec::Unknown)
+ Level = Right.getPrecedence();
+ if (Level == prec::Assignment)
+ return Style.PenaltyBreakAssignment;
+ if (Level != prec::Unknown)
+ return Level;
+
+ return 3;
+}
+
+bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
+ if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
+ return true;
+ if (Right.is(TT_OverloadedOperatorLParen) &&
+ Style.SpaceBeforeParensOptions.AfterOverloadedOperator) {
+ return true;
+ }
+ if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
+ Right.ParameterCount > 0) {
+ return true;
+ }
+ return false;
+}
+
+bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
+ const FormatToken &Left,
+ const FormatToken &Right) const {
+ if (Left.is(tok::kw_return) &&
+ Right.isNoneOf(tok::semi, tok::r_paren, tok::hashhash)) {
+ return true;
+ }
+ if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen &&
+ Right.MatchingParen->is(TT_CastRParen)) {
+ return true;
+ }
+ if (Left.is(Keywords.kw_assert) && Style.isJava())
+ return true;
+ if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
+ Left.is(tok::objc_property)) {
+ return true;
+ }
+ if (Right.is(tok::hashhash))
+ return Left.is(tok::hash);
+ if (Left.isOneOf(tok::hashhash, tok::hash))
+ return Right.is(tok::hash);
+ if (Style.SpacesInParens == FormatStyle::SIPO_Custom) {
+ if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
+ return Style.SpacesInParensOptions.InEmptyParentheses;
+ if (Style.SpacesInParensOptions.ExceptDoubleParentheses &&
+ Left.is(tok::r_paren) && Right.is(tok::r_paren)) {
+ auto *InnerLParen = Left.MatchingParen;
+ if (InnerLParen && InnerLParen->Previous == Right.MatchingParen) {
+ InnerLParen->SpacesRequiredBefore = 0;
+ return false;
+ }
+ }
+ const FormatToken *LeftParen = nullptr;
+ if (Left.is(tok::l_paren))
+ LeftParen = &Left;
+ else if (Right.is(tok::r_paren) && Right.MatchingParen)
+ LeftParen = Right.MatchingParen;
+ if (LeftParen && (LeftParen->is(TT_ConditionLParen) ||
+ (LeftParen->Previous &&
+ isKeywordWithCondition(*LeftParen->Previous)))) {
+ return Style.SpacesInParensOptions.InConditionalStatements;
+ }
+ }
+
+ // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
+ if (Left.is(tok::kw_auto) && Right.isOneOf(TT_LambdaLBrace, TT_FunctionLBrace,
+ // function return type 'auto'
+ TT_FunctionTypeLParen)) {
+ return true;
+ }
+
+ // auto{x} auto(x)
+ if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
+ return false;
+
+ const auto *BeforeLeft = Left.Previous;
+
+ // operator co_await(x)
+ if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && BeforeLeft &&
+ BeforeLeft->is(tok::kw_operator)) {
+ return false;
+ }
+ // co_await (x), co_yield (x), co_return (x)
+ if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
+ Right.isNoneOf(tok::semi, tok::r_paren)) {
+ return true;
+ }
+
+ if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) {
+ return (Right.is(TT_CastRParen) ||
+ (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
+ ? Style.SpacesInParensOptions.InCStyleCasts
+ : Style.SpacesInParensOptions.Other;
+ }
+
+
+ if (Style.SpaceAfterCompoundLiteralType && Left.is(tok::r_paren) &&
+ Left.MatchingParen && Left.MatchingParen->is(tok::l_paren) &&
+ Right.is(tok::l_brace)) {
+ return true;
+ }
+
+ if (Right.isOneOf(tok::semi, tok::comma))
+ return false;
+ if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
+ bool IsLightweightGeneric = Right.MatchingParen &&
+ Right.MatchingParen->Next &&
+ Right.MatchingParen->Next->is(tok::colon);
+ return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
+ }
+ if (Right.is(tok::less) && Left.is(tok::kw_template))
+ return Style.SpaceAfterTemplateKeyword;
+ if (Left.isOneOf(tok::exclaim, tok::tilde))
+ return false;
+ if (Left.is(tok::at) &&
+ Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
+ tok::numeric_constant, tok::l_paren, tok::l_brace,
+ tok::kw_true, tok::kw_false)) {
+ return false;
+ }
+ if (Left.is(tok::colon))
+ return Left.isNoneOf(TT_ObjCSelector, TT_ObjCMethodExpr);
+ if (Left.is(tok::coloncolon))
+ return false;
+ if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
+ if (Style.isTextProto() ||
+ (Style.Language == FormatStyle::LK_Proto &&
+ (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
+ // Format empty list as `<>`.
+ if (Left.is(tok::less) && Right.is(tok::greater))
+ return false;
+ return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
+ }
+ // Don't attempt to format operator<(), as it is handled later.
+ if (Right.isNot(TT_OverloadedOperatorLParen))
+ return false;
+ }
+ if (Right.is(tok::ellipsis)) {
+ return Left.Tok.isLiteral() || (Left.is(tok::identifier) && BeforeLeft &&
+ BeforeLeft->is(tok::kw_case));
+ }
+ if (Left.is(tok::l_square) && Right.is(tok::amp))
+ return Style.SpacesInSquareBrackets;
+ if (Right.is(TT_PointerOrReference)) {
+ if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
+ if (!Left.MatchingParen)
+ return true;
+ FormatToken *TokenBeforeMatchingParen =
+ Left.MatchingParen->getPreviousNonComment();
+ if (!TokenBeforeMatchingParen || Left.isNot(TT_TypeDeclarationParen))
+ return true;
+ }
+ // Add a space if the previous token is a pointer qualifier or the closing
+ // parenthesis of __attribute__(()) expression and the style requires spaces
+ // after pointer qualifiers.
+ if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
+ Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
+ (Left.is(TT_AttributeRParen) ||
+ Left.canBePointerOrReferenceQualifier())) {
+ return true;
+ }
+ if (Left.Tok.isLiteral())
+ return true;
+ // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
+ if (Left.isTypeOrIdentifier(LangOpts) && Right.Next && Right.Next->Next &&
+ Right.Next->Next->is(TT_RangeBasedForLoopColon)) {
+ return getTokenPointerOrReferenceAlignment(Right) !=
+ FormatStyle::PAS_Left;
+ }
+ return Left.isNoneOf(TT_PointerOrReference, tok::l_paren) &&
+ (getTokenPointerOrReferenceAlignment(Right) !=
+ FormatStyle::PAS_Left ||
+ (Line.IsMultiVariableDeclStmt &&
+ (Left.NestingLevel == 0 ||
+ (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
+ }
+ if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
+ (Left.isNot(TT_PointerOrReference) ||
+ (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
+ !Line.IsMultiVariableDeclStmt))) {
+ return true;
+ }
+ if (Left.is(TT_PointerOrReference)) {
+ // Add a space if the next token is a pointer qualifier and the style
+ // requires spaces before pointer qualifiers.
+ if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
+ Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
+ Right.canBePointerOrReferenceQualifier()) {
+ return true;
+ }
+ // & 1
+ if (Right.Tok.isLiteral())
+ return true;
+ // & /* comment
+ if (Right.is(TT_BlockComment))
+ return true;
+ // foo() -> const Bar * override/final
+ // S::foo() & noexcept/requires
+ if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final, tok::kw_noexcept,
+ TT_RequiresClause) &&
+ Right.isNot(TT_StartOfName)) {
+ return true;
+ }
+ // & {
+ if (Right.is(tok::l_brace) && Right.is(BK_Block))
+ return true;
+ // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
+ if (BeforeLeft && BeforeLeft->isTypeOrIdentifier(LangOpts) && Right.Next &&
+ Right.Next->is(TT_RangeBasedForLoopColon)) {
+ return getTokenPointerOrReferenceAlignment(Left) !=
+ FormatStyle::PAS_Right;
+ }
+ if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
+ tok::l_paren)) {
+ return false;
+ }
+ if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
+ return false;
+ // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone,
+ // because it does not take into account nested scopes like lambdas.
+ // In multi-variable declaration statements, attach */& to the variable
+ // independently of the style. However, avoid doing it if we are in a nested
+ // scope, e.g. lambda. We still need to special-case statements with
+ // initializers.
+ if (Line.IsMultiVariableDeclStmt &&
+ (Left.NestingLevel == Line.First->NestingLevel ||
+ ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
+ startsWithInitStatement(Line)))) {
+ return false;
+ }
+ if (!BeforeLeft)
+ return false;
+ if (BeforeLeft->is(tok::coloncolon)) {
+ if (Left.isNot(tok::star))
+ return false;
+ assert(Style.PointerAlignment != FormatStyle::PAS_Right);
+ if (!Right.startsSequence(tok::identifier, tok::r_paren))
+ return true;
+ assert(Right.Next);
+ const auto *LParen = Right.Next->MatchingParen;
+ return !LParen || LParen->isNot(TT_FunctionTypeLParen);
+ }
+ return BeforeLeft->isNoneOf(tok::l_paren, tok::l_square);
+ }
+ // Ensure right pointer alignment with ellipsis e.g. int *...P
+ if (Left.is(tok::ellipsis) && BeforeLeft &&
+ BeforeLeft->isPointerOrReference()) {
+ return Style.PointerAlignment != FormatStyle::PAS_Right;
+ }
+
+ if (Right.is(tok::star) && Left.is(tok::l_paren))
+ return false;
+ if (Left.is(tok::star) && Right.isPointerOrReference())
+ return false;
+ if (Right.isPointerOrReference()) {
+ const FormatToken *Previous = &Left;
+ while (Previous && Previous->isNot(tok::kw_operator)) {
+ if (Previous->is(tok::identifier) || Previous->isTypeName(LangOpts)) {
+ Previous = Previous->getPreviousNonComment();
+ continue;
+ }
+ if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
+ Previous = Previous->MatchingParen->getPreviousNonComment();
+ continue;
+ }
+ if (Previous->is(tok::coloncolon)) {
+ Previous = Previous->getPreviousNonComment();
+ continue;
+ }
+ break;
+ }
+ // Space between the type and the * in:
+ // operator void*()
+ // operator char*()
+ // operator void const*()
+ // operator void volatile*()
+ // operator /*comment*/ const char*()
+ // operator volatile /*comment*/ char*()
+ // operator Foo*()
+ // operator C<T>*()
+ // operator std::Foo*()
+ // operator C<T>::D<U>*()
+ // dependent on PointerAlignment style.
+ if (Previous) {
+ if (Previous->endsSequence(tok::kw_operator))
+ return Style.PointerAlignment != FormatStyle::PAS_Left;
+ if (Previous->isOneOf(tok::kw_const, tok::kw_volatile)) {
+ return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
+ (Style.SpaceAroundPointerQualifiers ==
+ FormatStyle::SAPQ_After) ||
+ (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
+ }
+ }
+ }
+ if (Style.isCSharp() && Left.is(Keywords.kw_is) && Right.is(tok::l_square))
+ return true;
+ const auto SpaceRequiredForArrayInitializerLSquare =
+ [](const FormatToken &LSquareTok, const FormatStyle &Style) {
+ return Style.SpacesInContainerLiterals ||
+ (Style.isProto() &&
+ Style.Cpp11BracedListStyle == FormatStyle::BLS_Block &&
+ LSquareTok.endsSequence(tok::l_square, tok::colon,
+ TT_SelectorName));
+ };
+ if (Left.is(tok::l_square)) {
+ return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
+ SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
+ (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
+ TT_LambdaLSquare) &&
+ Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
+ }
+ if (Right.is(tok::r_square)) {
+ return Right.MatchingParen &&
+ ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
+ SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
+ Style)) ||
+ (Style.SpacesInSquareBrackets &&
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare,
+ TT_LambdaLSquare)));
+ }
+ if (Right.is(tok::l_square) &&
+ Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare, TT_AttributeLSquare) &&
+ Left.isNoneOf(tok::numeric_constant, TT_DictLiteral) &&
+ !(Left.isNot(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
+ Right.is(TT_ArraySubscriptLSquare))) {
+ return false;
+ }
+ if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
+ (Right.is(tok::r_brace) && Right.MatchingParen &&
+ Right.MatchingParen->isNot(BK_Block))) {
+ return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block ||
+ Style.SpacesInParensOptions.Other;
+ }
+ if (Left.is(TT_BlockComment)) {
+ // No whitespace in x(/*foo=*/1), except for JavaScript.
+ return Style.isJavaScript() || !Left.TokenText.ends_with("=*/");
+ }
+
+ // Space between template and attribute.
+ // e.g. template <typename T> [[nodiscard]] ...
+ if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeLSquare))
+ return true;
+ // Space before parentheses common for all languages
+ if (Right.is(tok::l_paren)) {
+ // Function declaration or definition
+ if (Line.MightBeFunctionDecl && Right.is(TT_FunctionDeclarationLParen)) {
+ if (spaceRequiredBeforeParens(Right))
+ return true;
+ const auto &Options = Style.SpaceBeforeParensOptions;
+ return Line.mightBeFunctionDefinition()
+ ? Options.AfterFunctionDefinitionName
+ : Options.AfterFunctionDeclarationName;
+ }
+ if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
+ return spaceRequiredBeforeParens(Right);
+ if (Left.isOneOf(TT_RequiresClause,
+ TT_RequiresClauseInARequiresExpression)) {
+ return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (Left.is(TT_RequiresExpression)) {
+ return Style.SpaceBeforeParensOptions.AfterRequiresInExpression ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (Left.isOneOf(TT_AttributeRParen, TT_AttributeRSquare))
+ return true;
+ if (Left.is(TT_ForEachMacro)) {
+ return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (Left.is(TT_IfMacro)) {
+ return Style.SpaceBeforeParensOptions.AfterIfMacros ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+ Left.isPlacementOperator() &&
+ Right.isNot(TT_OverloadedOperatorLParen) &&
+ !(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+ const auto *RParen = Right.MatchingParen;
+ return Style.SpaceBeforeParensOptions.AfterPlacementOperator ||
+ (RParen && RParen->is(TT_CastRParen));
+ }
+ if (Line.Type == LT_ObjCDecl)
+ return true;
+ if (Left.is(tok::semi))
+ return true;
+ if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
+ tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) ||
+ Left.isIf(Line.Type != LT_PreprocessorDirective) ||
+ Right.is(TT_ConditionLParen)) {
+ return Style.SpaceBeforeParensOptions.AfterControlStatements ||
+ spaceRequiredBeforeParens(Right);
+ }
+
+ // TODO add Operator overloading specific Options to
+ // SpaceBeforeParensOptions
+ if (Right.is(TT_OverloadedOperatorLParen))
+ return spaceRequiredBeforeParens(Right);
+
+ // Lambda
+ if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
+ Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) {
+ return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (!BeforeLeft || BeforeLeft->isNoneOf(tok::period, tok::arrow)) {
+ if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
+ return Style.SpaceBeforeParensOptions.AfterControlStatements ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if (Left.isPlacementOperator() ||
+ (Left.is(tok::r_square) && Left.MatchingParen &&
+ Left.MatchingParen->Previous &&
+ Left.MatchingParen->Previous->is(tok::kw_delete))) {
+ return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
+ spaceRequiredBeforeParens(Right);
+ }
+ }
+ auto CompoundLiteral = [](const FormatToken &Tok) {
+ if (Tok.isNot(tok::l_paren))
+ return false;
+ const auto *RParen = Tok.MatchingParen;
+ if (!RParen)
+ return false;
+ const auto *Next = RParen->Next;
+ return Next && Next->is(tok::l_brace) && Next->is(BK_BracedInit);
+ };
+ if (Left.is(tok::kw_sizeof) && CompoundLiteral(Right))
+ return true;
+ // Handle builtins like identifiers.
+ if (Line.Type != LT_PreprocessorDirective &&
+ (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) {
+ return spaceRequiredBeforeParens(Right);
+ }
+ return false;
+ }
+ if (Left.is(tok::at) && Right.isNot(tok::objc_not_keyword))
+ return false;
+ if (Right.is(TT_UnaryOperator)) {
+ return Left.isNoneOf(tok::l_paren, tok::l_square, tok::at) &&
+ (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
+ }
+ // No space between the variable name and the initializer list.
+ // A a1{1};
+ // Verilog doesn't have such syntax, but it has word operators that are C++
+ // identifiers like `a inside {b, c}`. So the rule is not applicable.
+ if (!Style.isVerilog() &&
+ (Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
+ tok::r_paren) ||
+ Left.isTypeName(LangOpts)) &&
+ Right.is(tok::l_brace) && Right.getNextNonComment() &&
+ Right.isNot(BK_Block)) {
+ return false;
+ }
+ if (Left.is(tok::period) || Right.is(tok::period))
+ return false;
+ // u#str, U#str, L#str, u8#str
+ // uR#str, UR#str, LR#str, u8R#str
+ if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+ (Left.TokenText == "L" || Left.TokenText == "u" ||
+ Left.TokenText == "U" || Left.TokenText == "u8" ||
+ Left.TokenText == "LR" || Left.TokenText == "uR" ||
+ Left.TokenText == "UR" || Left.TokenText == "u8R")) {
+ return false;
+ }
+ if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
+ Left.MatchingParen->Previous &&
+ Left.MatchingParen->Previous->isOneOf(tok::period, tok::coloncolon)) {
+ // Java call to generic function with explicit type:
+ // A.<B<C<...>>>DoSomething();
+ // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
+ return false;
+ }
+ if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
+ return false;
+ if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) {
+ // Objective-C dictionary literal -> no space after opening brace.
+ return false;
+ }
+ if (Right.is(tok::r_brace) && Right.MatchingParen &&
+ Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) {
+ // Objective-C dictionary literal -> no space before closing brace.
+ return false;
+ }
+ if (Right.is(TT_TrailingAnnotation) && Right.isOneOf(tok::amp, tok::ampamp) &&
+ Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
+ (!Right.Next || Right.Next->is(tok::semi))) {
+ // Match const and volatile ref-qualifiers without any additional
+ // qualifiers such as
+ // void Fn() const &;
+ return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
+ }
+
+ return true;
+}
+
+bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
+ const FormatToken &Right) const {
+ const FormatToken &Left = *Right.Previous;
+
+ // If the token is finalized don't touch it (as it could be in a
+ // clang-format-off section).
+ if (Left.Finalized)
+ return Right.hasWhitespaceBefore();
+
+ const bool IsVerilog = Style.isVerilog();
+ assert(!IsVerilog || !IsCpp);
+
+ // Never ever merge two words.
+ if (Keywords.isWordLike(Right, IsVerilog) &&
+ Keywords.isWordLike(Left, IsVerilog)) {
+ return true;
+ }
+
+ // Leave a space between * and /* to avoid C4138 `comment end` found outside
+ // of comment.
+ if (Left.is(tok::star) && Right.is(tok::comment))
+ return true;
+
+ if (Left.is(tok::l_brace) && Right.is(tok::r_brace) &&
+ Left.Children.empty()) {
+ if (Left.is(BK_Block))
+ return Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never;
+ if (Style.Cpp11BracedListStyle != FormatStyle::BLS_Block) {
+ return Style.SpacesInParens == FormatStyle::SIPO_Custom &&
+ Style.SpacesInParensOptions.InEmptyParentheses;
+ }
+ return Style.SpaceInEmptyBraces == FormatStyle::SIEB_Always;
+ }
+
+ const auto *BeforeLeft = Left.Previous;
+
+ if (IsCpp) {
+ if (Left.is(TT_OverloadedOperator) &&
+ Right.isOneOf(TT_TemplateOpener, TT_TemplateCloser)) {
+ return true;
+ }
+ // Space between UDL and dot: auto b = 4s .count();
+ if (Right.is(tok::period) && Left.is(tok::numeric_constant))
+ return true;
+ // Space between import <iostream>.
+ // or import .....;
+ if (Left.is(Keywords.kw_import) &&
+ Right.isOneOf(tok::less, tok::ellipsis) &&
+ (!BeforeLeft || BeforeLeft->is(tok::kw_export))) {
+ return true;
+ }
+ // Space between `module :` and `import :`.
+ if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) &&
+ Right.is(TT_ModulePartitionColon)) {
+ return true;
+ }
+
+ if (Right.is(TT_AfterPPDirective))
+ return true;
+
+ // No space between import foo:bar but keep a space between import :bar;
+ if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
+ return false;
+ // No space between :bar;
+ if (Left.is(TT_ModulePartitionColon) &&
+ Right.isOneOf(tok::identifier, tok::kw_private)) {
+ return false;
+ }
+ if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
+ Line.First->is(Keywords.kw_import)) {
+ return false;
+ }
+ // Space in __attribute__((attr)) ::type.
+ if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
+ Right.is(tok::coloncolon)) {
+ return true;
+ }
+
+ if (Left.is(tok::kw_operator))
+ return Right.is(tok::coloncolon) || Style.SpaceAfterOperatorKeyword;
+ if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
+ !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) {
+ return true;
+ }
+ if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
+ Right.is(TT_TemplateOpener)) {
+ return true;
+ }
+ // C++ Core Guidelines suppression tag, e.g. `[[suppress(type.5)]]`.
+ if (Left.is(tok::identifier) && Right.is(tok::numeric_constant))
+ return Right.TokenText[0] != '.';
+ // `Left` is a keyword (including C++ alternative operator) or identifier.
+ if (Left.Tok.getIdentifierInfo() && Right.Tok.isLiteral())
+ return true;
+ } else if (Style.isProto()) {
+ if (Right.is(tok::period) && !(BeforeLeft && BeforeLeft->is(tok::period)) &&
+ Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
+ Keywords.kw_repeated, Keywords.kw_extend)) {
+ return true;
+ }
+ if (Right.is(tok::l_paren) &&
+ Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) {
+ return true;
+ }
+ if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
+ return true;
+ // Slashes occur in text protocol extension syntax: [type/type] { ... }.
+ if (Left.is(tok::slash) || Right.is(tok::slash))
+ return false;
+ if (Left.MatchingParen &&
+ Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
+ Right.isOneOf(tok::l_brace, tok::less)) {
+ return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
+ }
+ // A percent is probably part of a formatting specification, such as %lld.
+ if (Left.is(tok::percent))
+ return false;
+ // Preserve the existence of a space before a percent for cases like 0x%04x
+ // and "%d %d"
+ if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
+ return Right.hasWhitespaceBefore();
+ } else if (Style.isJson()) {
+ if (Right.is(tok::colon) && Left.is(tok::string_literal))
+ return Style.SpaceBeforeJsonColon;
+ } else if (Style.isCSharp()) {
+ // Require spaces around '{' and before '}' unless they appear in
+ // interpolated strings. Interpolated strings are merged into a single token
+ // so cannot have spaces inserted by this function.
+
+ // No space between 'this' and '['
+ if (Left.is(tok::kw_this) && Right.is(tok::l_square))
+ return false;
+
+ // No space between 'new' and '('
+ if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
+ return false;
+
+ // Space before { (including space within '{ {').
+ if (Right.is(tok::l_brace))
+ return true;
+
+ // Spaces inside braces.
+ if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
+ return true;
+
+ if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
+ return true;
+
+ // Spaces around '=>'.
+ if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
+ return true;
+
+ // No spaces around attribute target colons
+ if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
+ return false;
+
+ // space between type and variable e.g. Dictionary<string,string> foo;
+ if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
+ return true;
+
+ // spaces inside square brackets.
+ if (Left.is(tok::l_square) || Right.is(tok::r_square))
+ return Style.SpacesInSquareBrackets;
+
+ // No space before ? in nullable types.
+ if (Right.is(TT_CSharpNullable))
+ return false;
+
+ // No space before null forgiving '!'.
+ if (Right.is(TT_NonNullAssertion))
+ return false;
+
+ // No space between consecutive commas '[,,]'.
+ if (Left.is(tok::comma) && Right.is(tok::comma))
+ return false;
+
+ // space after var in `var (key, value)`
+ if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
+ return true;
+
+ // space between keywords and paren e.g. "using ("
+ if (Right.is(tok::l_paren)) {
+ if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
+ Keywords.kw_lock)) {
+ return Style.SpaceBeforeParensOptions.AfterControlStatements ||
+ spaceRequiredBeforeParens(Right);
+ }
+ }
+
+ // space between method modifier and opening parenthesis of a tuple return
+ // type
+ if ((Left.isAccessSpecifierKeyword() ||
+ Left.isOneOf(tok::kw_virtual, tok::kw_extern, tok::kw_static,
+ Keywords.kw_internal, Keywords.kw_abstract,
+ Keywords.kw_sealed, Keywords.kw_override,
+ Keywords.kw_async, Keywords.kw_unsafe)) &&
+ Right.is(tok::l_paren)) {
+ return true;
+ }
+ } else if (Style.isJavaScript()) {
+ if (Left.is(TT_FatArrow))
+ return true;
+ // for await ( ...
+ if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && BeforeLeft &&
+ BeforeLeft->is(tok::kw_for)) {
+ return true;
+ }
+ if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
+ Right.MatchingParen) {
+ const FormatToken *Next = Right.MatchingParen->getNextNonComment();
+ // An async arrow function, for example: `x = async () => foo();`,
+ // as opposed to calling a function called async: `x = async();`
+ if (Next && Next->is(TT_FatArrow))
+ return true;
+ }
+ if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
+ (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
+ return false;
+ }
+ // In tagged template literals ("html`bar baz`"), there is no space between
+ // the tag identifier and the template string.
+ if (Keywords.isJavaScriptIdentifier(Left,
+ /* AcceptIdentifierName= */ false) &&
+ Right.is(TT_TemplateString)) {
+ return false;
+ }
+ if (Right.is(tok::star) &&
+ Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) {
+ return false;
+ }
+ if (Right.isOneOf(tok::l_brace, tok::l_square) &&
+ Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
+ Keywords.kw_extends, Keywords.kw_implements)) {
+ return true;
+ }
+ if (Right.is(tok::l_paren)) {
+ // JS methods can use some keywords as names (e.g. `delete()`).
+ if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
+ return false;
+ // Valid JS method names can include keywords, e.g. `foo.delete()` or
+ // `bar.instanceof()`. Recognize call positions by preceding period.
+ if (BeforeLeft && BeforeLeft->is(tok::period) &&
+ Left.Tok.getIdentifierInfo()) {
+ return false;
+ }
+ // Additional unary JavaScript operators that need a space after.
+ if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
+ tok::kw_void)) {
+ return true;
+ }
+ }
+ // `foo as const;` casts into a const type.
+ if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
+ return false;
+ if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
+ tok::kw_const) ||
+ // "of" is only a keyword if it appears after another identifier
+ // (e.g. as "const x of y" in a for loop), or after a destructuring
+ // operation (const [x, y] of z, const {a, b} of c).
+ (Left.is(Keywords.kw_of) && BeforeLeft &&
+ BeforeLeft->isOneOf(tok::identifier, tok::r_square, tok::r_brace))) &&
+ (!BeforeLeft || BeforeLeft->isNot(tok::period))) {
+ return true;
+ }
+ if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && BeforeLeft &&
+ BeforeLeft->is(tok::period) && Right.is(tok::l_paren)) {
+ return false;
+ }
+ if (Left.is(Keywords.kw_as) &&
+ Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) {
+ return true;
+ }
+ if (Left.is(tok::kw_default) && BeforeLeft &&
+ BeforeLeft->is(tok::kw_export)) {
+ return true;
+ }
+ if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
+ return true;
+ if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
+ return false;
+ if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
+ return false;
+ if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
+ Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) {
+ return false;
+ }
+ if (Left.is(tok::ellipsis))
+ return false;
+ if (Left.is(TT_TemplateCloser) &&
+ Right.isNoneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
+ Keywords.kw_implements, Keywords.kw_extends)) {
+ // Type assertions ('<type>expr') are not followed by whitespace. Other
+ // locations that should have whitespace following are identified by the
+ // above set of follower tokens.
+ return false;
+ }
+ if (Right.is(TT_NonNullAssertion))
+ return false;
+ if (Left.is(TT_NonNullAssertion) &&
+ Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) {
+ return true; // "x! as string", "x! in y"
+ }
+ } else if (Style.isJava()) {
+ if (Left.is(TT_CaseLabelArrow) || Right.is(TT_CaseLabelArrow))
+ return true;
+ if (Left.is(tok::r_square) && Right.is(tok::l_brace))
+ return true;
+ // spaces inside square brackets.
+ if (Left.is(tok::l_square) || Right.is(tok::r_square))
+ return Style.SpacesInSquareBrackets;
+
+ if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) {
+ return Style.SpaceBeforeParensOptions.AfterControlStatements ||
+ spaceRequiredBeforeParens(Right);
+ }
+ if ((Left.isAccessSpecifierKeyword() ||
+ Left.isOneOf(tok::kw_static, Keywords.kw_final, Keywords.kw_abstract,
+ Keywords.kw_native)) &&
+ Right.is(TT_TemplateOpener)) {
+ return true;
+ }
+ } else if (IsVerilog) {
+ // An escaped identifier ends with whitespace.
+ if (Left.is(tok::identifier) && Left.TokenText[0] == '\\')
+ return true;
+ // Add space between things in a primitive's state table unless in a
+ // transition like `(0?)`.
+ if ((Left.is(TT_VerilogTableItem) &&
+ Right.isNoneOf(tok::r_paren, tok::semi)) ||
+ (Right.is(TT_VerilogTableItem) && Left.isNot(tok::l_paren))) {
+ const FormatToken *Next = Right.getNextNonComment();
+ return !(Next && Next->is(tok::r_paren));
+ }
+ // Don't add space within a delay like `#0`.
+ if (Left.isNot(TT_BinaryOperator) &&
+ Left.isOneOf(Keywords.kw_verilogHash, Keywords.kw_verilogHashHash)) {
+ return false;
+ }
+ // Add space after a delay.
+ if (Right.isNot(tok::semi) &&
+ (Left.endsSequence(tok::numeric_constant, Keywords.kw_verilogHash) ||
+ Left.endsSequence(tok::numeric_constant,
+ Keywords.kw_verilogHashHash) ||
+ (Left.is(tok::r_paren) && Left.MatchingParen &&
+ Left.MatchingParen->endsSequence(tok::l_paren, tok::at)))) {
+ return true;
+ }
+ // Don't add embedded spaces in a number literal like `16'h1?ax` or an array
+ // literal like `'{}`.
+ if (Left.is(Keywords.kw_apostrophe) ||
+ (Left.is(TT_VerilogNumberBase) && Right.is(tok::numeric_constant))) {
+ return false;
+ }
+ // Add spaces around the implication operator `->`.
+ if (Left.is(tok::arrow) || Right.is(tok::arrow))
+ return true;
+ // Don't add spaces between two at signs. Like in a coverage event.
+ // Don't add spaces between at and a sensitivity list like
+ // `@(posedge clk)`.
+ if (Left.is(tok::at) && Right.isOneOf(tok::l_paren, tok::star, tok::at))
+ return false;
+ // Add space between the type name and dimension like `logic [1:0]`.
+ if (Right.is(tok::l_square) &&
+ Left.isOneOf(TT_VerilogDimensionedTypeName, Keywords.kw_function)) {
+ return true;
+ }
+ // In a tagged union expression, there should be a space after the tag.
+ if (Right.isOneOf(tok::period, Keywords.kw_apostrophe) &&
+ Keywords.isVerilogIdentifier(Left) && Left.getPreviousNonComment() &&
+ Left.getPreviousNonComment()->is(Keywords.kw_tagged)) {
+ return true;
+ }
+ // Don't add spaces between a casting type and the quote or repetition count
+ // and the brace. The case of tagged union expressions is handled by the
+ // previous rule.
+ if ((Right.is(Keywords.kw_apostrophe) ||
+ (Right.is(BK_BracedInit) && Right.is(tok::l_brace))) &&
+ Left.isNoneOf(Keywords.kw_assign, Keywords.kw_unique) &&
+ !Keywords.isVerilogWordOperator(Left) &&
+ (Left.isOneOf(tok::r_square, tok::r_paren, tok::r_brace,
+ tok::numeric_constant) ||
+ Keywords.isWordLike(Left))) {
+ return false;
+ }
+ // Don't add spaces in imports like `import foo::*;`.
+ if ((Right.is(tok::star) && Left.is(tok::coloncolon)) ||
+ (Left.is(tok::star) && Right.is(tok::semi))) {
+ return false;
+ }
+ // Add space in attribute like `(* ASYNC_REG = "TRUE" *)`.
+ if (Left.endsSequence(tok::star, tok::l_paren) && Right.is(tok::identifier))
+ return true;
+ // Add space before drive strength like in `wire (strong1, pull0)`.
+ if (Right.is(tok::l_paren) && Right.is(TT_VerilogStrength))
+ return true;
+ // Don't add space in a streaming concatenation like `{>>{j}}`.
+ if ((Left.is(tok::l_brace) &&
+ Right.isOneOf(tok::lessless, tok::greatergreater)) ||
+ (Left.endsSequence(tok::lessless, tok::l_brace) ||
+ Left.endsSequence(tok::greatergreater, tok::l_brace))) {
+ return false;
+ }
+ } else if (Style.isTableGen()) {
+ // Avoid to connect [ and {. [{ is start token of multiline string.
+ if (Left.is(tok::l_square) && Right.is(tok::l_brace))
+ return true;
+ if (Left.is(tok::r_brace) && Right.is(tok::r_square))
+ return true;
+ // Do not insert around colon in DAGArg and cond operator.
+ if (Right.isOneOf(TT_TableGenDAGArgListColon,
+ TT_TableGenDAGArgListColonToAlign) ||
+ Left.isOneOf(TT_TableGenDAGArgListColon,
+ TT_TableGenDAGArgListColonToAlign)) {
+ return false;
+ }
+ if (Right.is(TT_TableGenCondOperatorColon))
+ return false;
+ if (Left.isOneOf(TT_TableGenDAGArgOperatorID,
+ TT_TableGenDAGArgOperatorToBreak) &&
+ Right.isNot(TT_TableGenDAGArgCloser)) {
+ return true;
+ }
+ // Do not insert bang operators and consequent openers.
+ if (Right.isOneOf(tok::l_paren, tok::less) &&
+ Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator)) {
+ return false;
+ }
+ // Trailing paste requires space before '{' or ':', the case in name values.
+ // Not before ';', the case in normal values.
+ if (Left.is(TT_TableGenTrailingPasteOperator) &&
+ Right.isOneOf(tok::l_brace, tok::colon)) {
+ return true;
+ }
+ // Otherwise paste operator does not prefer space around.
+ if (Left.is(tok::hash) || Right.is(tok::hash))
+ return false;
+ // Sure not to connect after defining keywords.
+ if (Keywords.isTableGenDefinition(Left))
+ return true;
+ }
+
+ if (Left.is(TT_ImplicitStringLiteral))
+ return Right.hasWhitespaceBefore();
+ if (Line.Type == LT_ObjCMethodDecl) {
+ if (Left.is(TT_ObjCMethodSpecifier))
+ return Style.ObjCSpaceAfterMethodDeclarationPrefix;
+ if (Left.is(tok::r_paren) && Left.isNot(TT_AttributeRParen) &&
+ canBeObjCSelectorComponent(Right)) {
+ // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
+ // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
+ // method declaration.
+ return false;
+ }
+ }
+ if (Line.Type == LT_ObjCProperty &&
+ (Right.is(tok::equal) || Left.is(tok::equal))) {
+ return false;
+ }
+
+ if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
+ Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) {
+ return true;
+ }
+ if (Left.is(tok::comma) && Right.isNot(TT_OverloadedOperatorLParen) &&
+ // In an unexpanded macro call we only find the parentheses and commas
+ // in a line; the commas and closing parenthesis do not require a space.
+ (Left.Children.empty() || !Left.MacroParent)) {
+ return true;
+ }
+ if (Right.is(tok::comma))
+ return false;
+ if (Right.is(TT_ObjCBlockLParen))
+ return true;
+ if (Right.is(TT_CtorInitializerColon))
+ return Style.SpaceBeforeCtorInitializerColon;
+ if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
+ return false;
+ if (Right.is(TT_RangeBasedForLoopColon) &&
+ !Style.SpaceBeforeRangeBasedForLoopColon) {
+ return false;
+ }
+ if (Left.is(TT_BitFieldColon)) {
+ return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+ Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
+ }
+ if (Right.is(tok::colon)) {
+ if (Right.is(TT_CaseLabelColon))
+ return Style.SpaceBeforeCaseColon;
+ if (Right.is(TT_GotoLabelColon))
+ return false;
+ // `private:` and `public:`.
+ if (!Right.getNextNonComment())
+ return false;
+ if (Right.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
+ return false;
+ if (Left.is(tok::question))
+ return false;
+ if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
+ return false;
+ if (Right.is(TT_DictLiteral))
+ return Style.SpacesInContainerLiterals;
+ if (Right.is(TT_AttributeColon))
+ return false;
+ if (Right.is(TT_CSharpNamedArgumentColon))
+ return false;
+ if (Right.is(TT_GenericSelectionColon))
+ return false;
+ if (Right.is(TT_BitFieldColon)) {
+ return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+ Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
+ }
+ return true;
+ }
+ // Do not merge "- -" into "--".
+ if ((Left.isOneOf(tok::minus, tok::minusminus) &&
+ Right.isOneOf(tok::minus, tok::minusminus)) ||
+ (Left.isOneOf(tok::plus, tok::plusplus) &&
+ Right.isOneOf(tok::plus, tok::plusplus))) {
+ return true;
+ }
+ if (Left.is(TT_UnaryOperator)) {
+ // Lambda captures allow for a lone &, so "&]" needs to be properly
+ // handled.
+ if (Left.is(tok::amp) && Right.is(tok::r_square))
+ return Style.SpacesInSquareBrackets;
+ if (Left.isNot(tok::exclaim))
+ return false;
+ if (Left.TokenText == "!")
+ return Style.SpaceAfterLogicalNot;
+ assert(Left.TokenText == "not");
+ return Right.isOneOf(tok::coloncolon, TT_UnaryOperator) ||
+ (Right.is(tok::l_paren) && Style.SpaceBeforeParensOptions.AfterNot);
+ }
+
+ // If the next token is a binary operator or a selector name, we have
+ // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
+ if (Left.is(TT_CastRParen)) {
+ // Compound literal: (Type) {init} — space controlled by dedicated option
+ if (Style.SpaceAfterCompoundLiteralType && Right.is(tok::l_brace))
+ return true;
+ return Style.SpaceAfterCStyleCast ||
+ Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
+ }
+
+ auto ShouldAddSpacesInAngles = [this, &Right]() {
+ if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
+ return true;
+ if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
+ return Right.hasWhitespaceBefore();
+ return false;
+ };
+
+ if (Left.is(tok::greater) && Right.is(tok::greater)) {
+ if (Style.isTextProto() ||
+ (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) {
+ return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
+ }
+ return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
+ ((Style.Standard < FormatStyle::LS_Cpp11) ||
+ ShouldAddSpacesInAngles());
+ }
+ if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
+ Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
+ (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) {
+ return false;
+ }
+ if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
+ Right.getPrecedence() == prec::Assignment) {
+ return false;
+ }
+ if (Style.isJava() && Right.is(tok::coloncolon) &&
+ Left.isOneOf(tok::identifier, tok::kw_this)) {
+ return false;
+ }
+ if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) {
+ // Generally don't remove existing spaces between an identifier and "::".
+ // The identifier might actually be a macro name such as ALWAYS_INLINE. If
+ // this turns out to be too lenient, add analysis of the identifier itself.
+ return Right.hasWhitespaceBefore();
+ }
+ if (Right.is(tok::coloncolon) &&
+ Left.isNoneOf(tok::l_brace, tok::comment, tok::l_paren)) {
+ // Put a space between < and :: in vector< ::std::string >
+ return (Left.is(TT_TemplateOpener) &&
+ ((Style.Standard < FormatStyle::LS_Cpp11) ||
+ ShouldAddSpacesInAngles())) ||
+ Left.isNoneOf(tok::l_paren, tok::r_paren, tok::l_square,
+ tok::kw___super, TT_TemplateOpener,
+ TT_TemplateCloser) ||
+ (Left.is(tok::l_paren) && Style.SpacesInParensOptions.Other);
+ }
+ if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
+ return ShouldAddSpacesInAngles();
+ if (Left.is(tok::r_paren) && Left.isNot(TT_TypeDeclarationParen) &&
+ Right.is(TT_PointerOrReference) && Right.isOneOf(tok::amp, tok::ampamp)) {
+ return true;
+ }
+ // Space before TT_StructuredBindingLSquare.
+ if (Right.is(TT_StructuredBindingLSquare)) {
+ return Left.isNoneOf(tok::amp, tok::ampamp) ||
+ getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
+ }
+ // Space before & or && following a TT_StructuredBindingLSquare.
+ if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
+ Right.isOneOf(tok::amp, tok::ampamp)) {
+ return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
+ }
+ if ((Right.is(TT_BinaryOperator) && Left.isNot(tok::l_paren)) ||
+ (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
+ Right.isNot(tok::r_paren))) {
+ return true;
+ }
+ if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
+ Left.MatchingParen &&
+ Left.MatchingParen->is(TT_OverloadedOperatorLParen)) {
+ return false;
+ }
+ if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
+ Line.Type == LT_ImportStatement) {
+ return true;
+ }
+ if (Right.is(TT_TrailingUnaryOperator))
+ return false;
+ if (Left.is(TT_RegexLiteral))
+ return false;
+ return spaceRequiredBetween(Line, Left, Right);
+}
+
+// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
+static bool isAllmanBrace(const FormatToken &Tok) {
+ return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
+ Tok.isNoneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
+}
+
+// Returns 'true' if 'Tok' is a function argument.
+static bool IsFunctionArgument(const FormatToken &Tok) {
+ return Tok.MatchingParen && Tok.MatchingParen->Next &&
+ Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren,
+ tok::r_brace);
+}
+
+static bool
+isEmptyLambdaAllowed(const FormatToken &Tok,
+ FormatStyle::ShortLambdaStyle ShortLambdaOption) {
+ return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
+}
+
+static bool isAllmanLambdaBrace(const FormatToken &Tok) {
+ return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
+ Tok.isNoneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
+}
+
+bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line,
+ const FormatToken &Right) const {
+ if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0 &&
+ (!Style.RemoveEmptyLinesInUnwrappedLines || &Right == Line.First)) {
+ return true;
+ }
+
+ const FormatToken &Left = *Right.Previous;
+
+ if (Style.BreakFunctionDefinitionParameters && Line.MightBeFunctionDecl &&
+ Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
+ Left.ParameterCount > 0) {
+ return true;
+ }
+
+ // Ignores the first parameter as this will be handled separately by
+ // BreakFunctionDefinitionParameters or AlignAfterOpenBracket.
+ if (Style.BinPackParameters == FormatStyle::BPPS_AlwaysOnePerLine &&
+ Line.MightBeFunctionDecl && !Left.opensScope() &&
+ startsNextParameter(Right, Style)) {
+ return true;
+ }
+
+ const auto *BeforeLeft = Left.Previous;
+ const auto *AfterRight = Right.Next;
+
+ if (Style.isCSharp()) {
+ if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
+ Style.BraceWrapping.AfterFunction) {
+ return true;
+ }
+ if (Right.is(TT_CSharpNamedArgumentColon) ||
+ Left.is(TT_CSharpNamedArgumentColon)) {
+ return false;
+ }
+ if (Right.is(TT_CSharpGenericTypeConstraint))
+ return true;
+ if (AfterRight && AfterRight->is(TT_FatArrow) &&
+ (Right.is(tok::numeric_constant) ||
+ (Right.is(tok::identifier) && Right.TokenText == "_"))) {
+ return true;
+ }
+
+ // Break after C# [...] and before public/protected/private/internal.
+ if (Left.is(TT_AttributeRSquare) &&
+ (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
+ Right.is(Keywords.kw_internal))) {
+ return true;
+ }
+ // Break between ] and [ but only when there are really 2 attributes.
+ if (Left.is(TT_AttributeRSquare) && Right.is(TT_AttributeLSquare))
+ return true;
+ } else if (Style.isJavaScript()) {
+ // FIXME: This might apply to other languages and token kinds.
+ if (Right.is(tok::string_literal) && Left.is(tok::plus) && BeforeLeft &&
+ BeforeLeft->is(tok::string_literal)) {
+ return true;
+ }
+ if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
+ BeforeLeft && BeforeLeft->is(tok::equal) &&
+ Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
+ tok::kw_const) &&
+ // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
+ // above.
+ Line.First->isNoneOf(Keywords.kw_var, Keywords.kw_let)) {
+ // Object literals on the top level of a file are treated as "enum-style".
+ // Each key/value pair is put on a separate line, instead of bin-packing.
+ return true;
+ }
+ if (Left.is(tok::l_brace) && Line.Level == 0 &&
+ (Line.startsWith(tok::kw_enum) ||
+ Line.startsWith(tok::kw_const, tok::kw_enum) ||
+ Line.startsWith(tok::kw_export, tok::kw_enum) ||
+ Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) {
+ // JavaScript top-level enum key/value pairs are put on separate lines
+ // instead of bin-packing.
+ return true;
+ }
+ if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && BeforeLeft &&
+ BeforeLeft->is(TT_FatArrow)) {
+ // JS arrow function (=> {...}).
+ switch (Style.AllowShortLambdasOnASingleLine) {
+ case FormatStyle::SLS_All:
+ return false;
+ case FormatStyle::SLS_None:
+ return true;
+ case FormatStyle::SLS_Empty:
+ return !Left.Children.empty();
+ case FormatStyle::SLS_Inline:
+ // allow one-lining inline (e.g. in function call args) and empty arrow
+ // functions.
+ return (Left.NestingLevel == 0 && Line.Level == 0) &&
+ !Left.Children.empty();
+ }
+ llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
+ }
+
+ if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
+ !Left.Children.empty()) {
+ // Support AllowShortFunctionsOnASingleLine for JavaScript.
+ if (Left.NestingLevel == 0 && Line.Level == 0)
+ return !Style.AllowShortFunctionsOnASingleLine.Other;
+
+ return !Style.AllowShortFunctionsOnASingleLine.Inline;
+ }
+ } else if (Style.isJava()) {
+ if (Right.is(tok::plus) && Left.is(tok::string_literal) && AfterRight &&
+ AfterRight->is(tok::string_literal)) {
+ return true;
+ }
+ } else if (Style.isVerilog()) {
+ // Break between assignments.
+ if (Left.is(TT_VerilogAssignComma))
+ return true;
+ // Break between ports of different types.
+ if (Left.is(TT_VerilogTypeComma))
+ return true;
+ // Break between ports in a module instantiation and after the parameter
+ // list.
+ if (Style.VerilogBreakBetweenInstancePorts &&
+ (Left.is(TT_VerilogInstancePortComma) ||
+ (Left.is(tok::r_paren) && Keywords.isVerilogIdentifier(Right) &&
+ Left.MatchingParen &&
+ Left.MatchingParen->is(TT_VerilogInstancePortLParen)))) {
+ return true;
+ }
+ // Break after labels. In Verilog labels don't have the 'case' keyword, so
+ // it is hard to identify them in UnwrappedLineParser.
+ if (!Keywords.isVerilogBegin(Right) && Keywords.isVerilogEndOfLabel(Left))
+ return true;
+ } else if (Style.BreakAdjacentStringLiterals &&
+ (IsCpp || Style.isProto() || Style.isTableGen())) {
+ if (Left.isStringLiteral() && Right.isStringLiteral())
+ return true;
+ }
+
+ // Basic JSON newline processing.
+ if (Style.isJson()) {
+ // Always break after a JSON record opener.
+ // {
+ // }
+ if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
+ return true;
+ // Always break after a JSON array opener based on BreakArrays.
+ if ((Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
+ Right.isNot(tok::r_square)) ||
+ Left.is(tok::comma)) {
+ if (Right.is(tok::l_brace))
+ return true;
+ // scan to the right if an we see an object or an array inside
+ // then break.
+ for (const auto *Tok = &Right; Tok; Tok = Tok->Next) {
+ if (Tok->isOneOf(tok::l_brace, tok::l_square))
+ return true;
+ if (Tok->isOneOf(tok::r_brace, tok::r_square))
+ break;
+ }
+ return Style.BreakArrays;
+ }
+ } else if (Style.isTableGen()) {
+ // Break the comma in side cond operators.
+ // !cond(case1:1,
+ // case2:0);
+ if (Left.is(TT_TableGenCondOperatorComma))
+ return true;
+ if (Left.is(TT_TableGenDAGArgOperatorToBreak) &&
+ Right.isNot(TT_TableGenDAGArgCloser)) {
+ return true;
+ }
+ if (Left.is(TT_TableGenDAGArgListCommaToBreak))
+ return true;
+ if (Right.is(TT_TableGenDAGArgCloser) && Right.MatchingParen &&
+ Right.MatchingParen->is(TT_TableGenDAGArgOpenerToBreak) &&
+ &Left != Right.MatchingParen->Next) {
+ // Check to avoid empty DAGArg such as (ins).
+ return Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll;
+ }
+ }
+
+ if (Line.startsWith(tok::kw_asm) && Right.is(TT_InlineASMColon) &&
+ Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always) {
+ return true;
+ }
+
+ // If the last token before a '}', ']', or ')' is a comma or a trailing
+ // comment, the intention is to insert a line break after it in order to make
+ // shuffling around entries easier. Import statements, especially in
+ // JavaScript, can be an exception to this rule.
+ if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
+ const FormatToken *BeforeClosingBrace = nullptr;
+ if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
+ (Style.isJavaScript() && Left.is(tok::l_paren))) &&
+ Left.isNot(BK_Block) && Left.MatchingParen) {
+ BeforeClosingBrace = Left.MatchingParen->Previous;
+ } else if (Right.MatchingParen &&
+ (Right.MatchingParen->isOneOf(tok::l_brace,
+ TT_ArrayInitializerLSquare) ||
+ (Style.isJavaScript() &&
+ Right.MatchingParen->is(tok::l_paren)))) {
+ BeforeClosingBrace = &Left;
+ }
+ if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
+ BeforeClosingBrace->isTrailingComment())) {
+ return true;
+ }
+ }
+
+ if (Right.is(tok::comment)) {
+ return Left.isNoneOf(BK_BracedInit, TT_CtorInitializerColon) &&
+ Right.NewlinesBefore > 0 && Right.HasUnescapedNewline;
+ }
+ if (Left.isTrailingComment())
+ return true;
+ if (Left.IsUnterminatedLiteral)
+ return true;
+
+ if (BeforeLeft && BeforeLeft->is(tok::lessless) &&
+ Left.is(tok::string_literal) && Right.is(tok::lessless) && AfterRight &&
+ AfterRight->is(tok::string_literal)) {
+ return Right.NewlinesBefore > 0;
+ }
+
+ if (Right.is(TT_RequiresClause)) {
+ switch (Style.RequiresClausePosition) {
+ case FormatStyle::RCPS_OwnLine:
+ case FormatStyle::RCPS_OwnLineWithBrace:
+ case FormatStyle::RCPS_WithFollowing:
+ return true;
+ default:
+ break;
+ }
+ }
+ // Can break after template<> declaration
+ if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
+ Left.MatchingParen->NestingLevel == 0) {
+ // Put concepts on the next line e.g.
+ // template<typename T>
+ // concept ...
+ if (Right.is(tok::kw_concept))
+ return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
+ return Style.BreakTemplateDeclarations == FormatStyle::BTDS_Yes ||
+ (Style.BreakTemplateDeclarations == FormatStyle::BTDS_Leave &&
+ Right.NewlinesBefore > 0);
+ }
+ if (Left.ClosesRequiresClause) {
+ switch (Style.RequiresClausePosition) {
+ case FormatStyle::RCPS_OwnLine:
+ case FormatStyle::RCPS_WithPreceding:
+ return Right.isNot(tok::semi);
+ case FormatStyle::RCPS_OwnLineWithBrace:
+ return Right.isNoneOf(tok::semi, tok::l_brace);
+ default:
+ break;
+ }
+ }
+ if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
+ if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
+ (Left.is(TT_CtorInitializerComma) ||
+ Right.is(TT_CtorInitializerColon))) {
+ return true;
+ }
+
+ if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
+ Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) {
+ return true;
+ }
+
+ if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterComma &&
+ Left.is(TT_CtorInitializerComma)) {
+ return true;
+ }
+ }
+ if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
+ Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) {
+ return true;
+ }
+ if (Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly) {
+ if ((Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon ||
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) &&
+ Right.is(TT_CtorInitializerColon)) {
+ return true;
+ }
+
+ if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
+ Left.is(TT_CtorInitializerColon)) {
+ return true;
+ }
+ }
+ // Break only if we have multiple inheritance.
+ if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
+ Right.is(TT_InheritanceComma)) {
+ return true;
+ }
+ if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
+ Left.is(TT_InheritanceComma)) {
+ return true;
+ }
+ if (Right.is(tok::string_literal) && Right.TokenText.starts_with("R\"")) {
+ // Multiline raw string literals are special wrt. line breaks. The author
+ // has made a deliberate choice and might have aligned the contents of the
+ // string literal accordingly. Thus, we try keep existing line breaks.
+ return Right.IsMultiline && Right.NewlinesBefore > 0;
+ }
+ if ((Left.is(tok::l_brace) ||
+ (Left.is(tok::less) && BeforeLeft && BeforeLeft->is(tok::equal))) &&
+ Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
+ // Don't put enums or option definitions onto single lines in protocol
+ // buffers.
+ return true;
+ }
+ if (Right.is(TT_InlineASMBrace))
+ return Right.HasUnescapedNewline;
+
+ if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
+ auto *FirstNonComment = Line.getFirstNonComment();
+ bool AccessSpecifier =
+ FirstNonComment && (FirstNonComment->is(Keywords.kw_internal) ||
+ FirstNonComment->isAccessSpecifierKeyword());
+
+ if (Style.BraceWrapping.AfterEnum) {
+ if (Line.startsWith(tok::kw_enum) ||
+ Line.startsWith(tok::kw_typedef, tok::kw_enum) ||
+ Line.startsWith(tok::kw_export, tok::kw_enum)) {
+ return true;
+ }
+ // Ensure BraceWrapping for `public enum A {`.
+ if (AccessSpecifier && FirstNonComment->Next &&
+ FirstNonComment->Next->is(tok::kw_enum)) {
+ return true;
+ }
+ }
+
+ // Ensure BraceWrapping for `public interface A {`.
+ if (Style.BraceWrapping.AfterClass &&
+ ((AccessSpecifier && FirstNonComment->Next &&
+ FirstNonComment->Next->is(Keywords.kw_interface)) ||
+ Line.startsWith(Keywords.kw_interface))) {
+ return true;
+ }
+
+ // Don't attempt to interpret record return types as records.
+ if (Right.isNot(TT_FunctionLBrace)) {
+ return Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Never &&
+ ((Line.startsWith(tok::kw_class) &&
+ Style.BraceWrapping.AfterClass) ||
+ (Line.startsWith(tok::kw_struct) &&
+ Style.BraceWrapping.AfterStruct) ||
+ (Line.startsWith(tok::kw_union) &&
+ Style.BraceWrapping.AfterUnion));
+ }
+ }
+
+ if (Left.is(TT_ObjCBlockLBrace) &&
+ Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
+ return true;
+ }
+
+ // Ensure wrapping after __attribute__((XX)) and @interface etc.
+ if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
+ Right.is(TT_ObjCDecl)) {
+ return true;
+ }
+
+ if (Left.is(TT_LambdaLBrace)) {
+ if (IsFunctionArgument(Left) &&
+ Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) {
+ return false;
+ }
+
+ if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
+ Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
+ (!Left.Children.empty() &&
+ Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) {
+ return true;
+ }
+ }
+
+ if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
+ (Left.isPointerOrReference() || Left.is(TT_TemplateCloser))) {
+ return true;
+ }
+
+ // Put multiple Java annotation on a new line.
+ if ((Style.isJava() || Style.isJavaScript()) &&
+ Left.is(TT_LeadingJavaAnnotation) &&
+ Right.isNoneOf(TT_LeadingJavaAnnotation, tok::l_paren) &&
+ (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) {
+ return true;
+ }
+
+ if (Right.is(TT_ProtoExtensionLSquare))
+ return true;
+
+ // In text proto instances if a submessage contains at least 2 entries and at
+ // least one of them is a submessage, like A { ... B { ... } ... },
+ // put all of the entries of A on separate lines by forcing the selector of
+ // the submessage B to be put on a newline.
+ //
+ // Example: these can stay on one line:
+ // a { scalar_1: 1 scalar_2: 2 }
+ // a { b { key: value } }
+ //
+ // and these entries need to be on a new line even if putting them all in one
+ // line is under the column limit:
+ // a {
+ // scalar: 1
+ // b { key: value }
+ // }
+ //
+ // We enforce this by breaking before a submessage field that has previous
+ // siblings, *and* breaking before a field that follows a submessage field.
+ //
+ // Be careful to exclude the case [proto.ext] { ... } since the `]` is
+ // the TT_SelectorName there, but we don't want to break inside the brackets.
+ //
+ // Another edge case is @submessage { key: value }, which is a common
+ // substitution placeholder. In this case we want to keep `@` and `submessage`
+ // together.
+ //
+ // We ensure elsewhere that extensions are always on their own line.
+ if (Style.isProto() && Right.is(TT_SelectorName) &&
+ Right.isNot(tok::r_square) && AfterRight) {
+ // Keep `@submessage` together in:
+ // @submessage { key: value }
+ if (Left.is(tok::at))
+ return false;
+ // Look for the scope opener after selector in cases like:
+ // selector { ...
+ // selector: { ...
+ // selector: @base { ...
+ const auto *LBrace = AfterRight;
+ if (LBrace && LBrace->is(tok::colon)) {
+ LBrace = LBrace->Next;
+ if (LBrace && LBrace->is(tok::at)) {
+ LBrace = LBrace->Next;
+ if (LBrace)
+ LBrace = LBrace->Next;
+ }
+ }
+ if (LBrace &&
+ // The scope opener is one of {, [, <:
+ // selector { ... }
+ // selector [ ... ]
+ // selector < ... >
+ //
+ // In case of selector { ... }, the l_brace is TT_DictLiteral.
+ // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
+ // so we check for immediately following r_brace.
+ ((LBrace->is(tok::l_brace) &&
+ (LBrace->is(TT_DictLiteral) ||
+ (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
+ LBrace->isOneOf(TT_ArrayInitializerLSquare, tok::less))) {
+ // If Left.ParameterCount is 0, then this submessage entry is not the
+ // first in its parent submessage, and we want to break before this entry.
+ // If Left.ParameterCount is greater than 0, then its parent submessage
+ // might contain 1 or more entries and we want to break before this entry
+ // if it contains at least 2 entries. We deal with this case later by
+ // detecting and breaking before the next entry in the parent submessage.
+ if (Left.ParameterCount == 0)
+ return true;
+ // However, if this submessage is the first entry in its parent
+ // submessage, Left.ParameterCount might be 1 in some cases.
+ // We deal with this case later by detecting an entry
+ // following a closing paren of this submessage.
+ }
+
+ // If this is an entry immediately following a submessage, it will be
+ // preceded by a closing paren of that submessage, like in:
+ // left---. .---right
+ // v v
+ // sub: { ... } key: value
+ // If there was a comment between `}` an `key` above, then `key` would be
+ // put on a new line anyways.
+ if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
+ return true;
+ }
+
+ if (Style.BreakAfterAttributes == FormatStyle::ABS_LeaveAll &&
+ Left.is(TT_AttributeRSquare) && Right.NewlinesBefore > 0) {
+ Line.ReturnTypeWrapped = true;
+ return true;
+ }
+
+ return false;
+}
+
+bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
+ const FormatToken &Right) const {
+ const FormatToken &Left = *Right.Previous;
+ // Language-specific stuff.
+ if (Style.isCSharp()) {
+ if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
+ Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) {
+ return false;
+ }
+ // Only break after commas for generic type constraints.
+ if (Line.First->is(TT_CSharpGenericTypeConstraint))
+ return Left.is(TT_CSharpGenericTypeConstraintComma);
+ // Keep nullable operators attached to their identifiers.
+ if (Right.is(TT_CSharpNullable))
+ return false;
+ } else if (Style.isJava()) {
+ if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
+ Keywords.kw_implements)) {
+ return false;
+ }
+ if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
+ Keywords.kw_implements)) {
+ return true;
+ }
+ } else if (Style.isJavaScript()) {
+ const FormatToken *NonComment = Right.getPreviousNonComment();
+ if (NonComment &&
+ (NonComment->isAccessSpecifierKeyword() ||
+ NonComment->isOneOf(
+ tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
+ tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
+ tok::kw_static, Keywords.kw_readonly, Keywords.kw_override,
+ Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set,
+ Keywords.kw_async, Keywords.kw_await))) {
+ return false; // Otherwise automatic semicolon insertion would trigger.
+ }
+ if (Right.NestingLevel == 0 &&
+ (Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+ Right.isOneOf(tok::l_square, tok::l_paren)) {
+ return false; // Otherwise automatic semicolon insertion would trigger.
+ }
+ if (NonComment && NonComment->is(tok::identifier) &&
+ NonComment->TokenText == "asserts") {
+ return false;
+ }
+ if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
+ return false;
+ if (Left.is(TT_JsTypeColon))
+ return true;
+ // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
+ if (Left.is(tok::exclaim) && Right.is(tok::colon))
+ return false;
+ // Look for is type annotations like:
+ // function f(): a is B { ... }
+ // Do not break before is in these cases.
+ if (Right.is(Keywords.kw_is)) {
+ const FormatToken *Next = Right.getNextNonComment();
+ // If `is` is followed by a colon, it's likely that it's a dict key, so
+ // ignore it for this check.
+ // For example this is common in Polymer:
+ // Polymer({
+ // is: 'name',
+ // ...
+ // });
+ if (!Next || Next->isNot(tok::colon))
+ return false;
+ }
+ if (Left.is(Keywords.kw_in))
+ return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
+ if (Right.is(Keywords.kw_in))
+ return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
+ if (Right.is(Keywords.kw_as))
+ return false; // must not break before as in 'x as type' casts
+ if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
+ // extends and infer can appear as keywords in conditional types:
+ // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
+ // do not break before them, as the expressions are subject to ASI.
+ return false;
+ }
+ if (Left.is(Keywords.kw_as))
+ return true;
+ if (Left.is(TT_NonNullAssertion))
+ return true;
+ if (Left.is(Keywords.kw_declare) &&
+ Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
+ Keywords.kw_function, tok::kw_class, tok::kw_enum,
+ Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
+ Keywords.kw_let, tok::kw_const)) {
+ // See grammar for 'declare' statements at:
+ // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
+ return false;
+ }
+ if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
+ Right.isOneOf(tok::identifier, tok::string_literal)) {
+ return false; // must not break in "module foo { ...}"
+ }
+ if (Right.is(TT_TemplateString) && Right.closesScope())
+ return false;
+ // Don't split tagged template literal so there is a break between the tag
+ // identifier and template string.
+ if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
+ return false;
+ if (Left.is(TT_TemplateString) && Left.opensScope())
+ return true;
+ } else if (Style.isTableGen()) {
+ // Avoid to break after "def", "class", "let" and so on.
+ if (Keywords.isTableGenDefinition(Left))
+ return false;
+ // Avoid to break after '(' in the cases that is in bang operators.
+ if (Right.is(tok::l_paren)) {
+ return Left.isNoneOf(TT_TableGenBangOperator, TT_TableGenCondOperator,
+ TT_TemplateCloser);
+ }
+ // Avoid to break between the value and its suffix part.
+ if (Left.is(TT_TableGenValueSuffix))
+ return false;
+ // Avoid to break around paste operator.
+ if (Left.is(tok::hash) || Right.is(tok::hash))
+ return false;
+ if (Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator))
+ return false;
+ }
+
+ // We can break before an r_brace if there was a break after the matching
+ // l_brace, which is tracked by BreakBeforeClosingBrace, or if we are in a
+ // block-indented initialization list.
+ if (Right.is(tok::r_brace)) {
+ return Right.MatchingParen && (Right.MatchingParen->is(BK_Block) ||
+ (Right.isBlockIndentedInitRBrace(Style)));
+ }
+
+ // We can break before r_paren if we're in a block indented context or
+ // a control statement with an explicit style option.
+ if (Right.is(tok::r_paren)) {
+ if (!Right.MatchingParen)
+ return false;
+ auto Next = Right.Next;
+ if (Next && Next->is(tok::r_paren))
+ Next = Next->Next;
+ if (Next && Next->is(tok::l_paren))
+ return false;
+ const FormatToken *Previous = Right.MatchingParen->Previous;
+ if (!Previous)
+ return false;
+ if (Previous->isIf())
+ return Style.BreakBeforeCloseBracketIf;
+ if (Previous->isLoop(Style))
+ return Style.BreakBeforeCloseBracketLoop;
+ if (Previous->is(tok::kw_switch))
+ return Style.BreakBeforeCloseBracketSwitch;
+ return Style.BreakBeforeCloseBracketFunction;
+ }
+
+ if (Left.isOneOf(tok::r_paren, TT_TrailingAnnotation) &&
+ Right.is(TT_TrailingAnnotation) &&
+ Style.BreakBeforeCloseBracketFunction) {
+ return false;
+ }
+
+ if (Right.is(TT_TemplateCloser))
+ return Style.BreakBeforeTemplateCloser;
+
+ if (Left.isOneOf(tok::at, tok::objc_interface))
+ return false;
+ if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
+ return Right.isNot(tok::l_paren);
+ if (Right.is(TT_PointerOrReference)) {
+ return Line.IsMultiVariableDeclStmt ||
+ (getTokenPointerOrReferenceAlignment(Right) ==
+ FormatStyle::PAS_Right &&
+ !(Right.Next &&
+ Right.Next->isOneOf(TT_FunctionDeclarationName, tok::kw_const)));
+ }
+ if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
+ TT_ClassHeadName, TT_QtProperty, tok::kw_operator)) {
+ return true;
+ }
+ if (Left.is(TT_PointerOrReference))
+ return false;
+ if (Right.isTrailingComment()) {
+ // We rely on MustBreakBefore being set correctly here as we should not
+ // change the "binding" behavior of a comment.
+ // The first comment in a braced lists is always interpreted as belonging to
+ // the first list element. Otherwise, it should be placed outside of the
+ // list.
+ return Left.is(BK_BracedInit) ||
+ (Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
+ }
+ if (Left.is(tok::question) && Right.is(tok::colon))
+ return false;
+ if (Right.isOneOf(TT_ConditionalExpr, tok::question))
+ return Style.BreakBeforeTernaryOperators;
+ if (Left.isOneOf(TT_ConditionalExpr, tok::question))
+ return !Style.BreakBeforeTernaryOperators;
+ if (Left.is(TT_InheritanceColon))
+ return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
+ if (Right.is(TT_InheritanceColon))
+ return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
+ // When the method parameter has no name, allow breaking before the colon.
+ if (Right.is(TT_ObjCMethodExpr) && Right.isNot(tok::r_square) &&
+ Left.isNot(TT_SelectorName)) {
+ return true;
+ }
+
+ if (Right.is(tok::colon) &&
+ Right.isNoneOf(TT_CtorInitializerColon, TT_InlineASMColon,
+ TT_BitFieldColon)) {
+ return false;
+ }
+ if (Left.is(tok::colon) && Left.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
+ return true;
+ if (Left.is(tok::colon) && Left.is(TT_DictLiteral)) {
+ if (Style.isProto()) {
+ if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+ return false;
+ // Prevent cases like:
+ //
+ // submessage:
+ // { key: valueeeeeeeeeeee }
+ //
+ // when the snippet does not fit into one line.
+ // Prefer:
+ //
+ // submessage: {
+ // key: valueeeeeeeeeeee
+ // }
+ //
+ // instead, even if it is longer by one line.
+ //
+ // Note that this allows the "{" to go over the column limit
+ // when the column limit is just between ":" and "{", but that does
+ // not happen too often and alternative formattings in this case are
+ // not much better.
+ //
+ // The code covers the cases:
+ //
+ // submessage: { ... }
+ // submessage: < ... >
+ // repeated: [ ... ]
+ if ((Right.isOneOf(tok::l_brace, tok::less) &&
+ Right.is(TT_DictLiteral)) ||
+ Right.is(TT_ArrayInitializerLSquare)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ if (Right.is(tok::r_square) && Right.MatchingParen &&
+ Right.MatchingParen->is(TT_ProtoExtensionLSquare)) {
+ return false;
+ }
+ if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
+ Right.Next->is(TT_ObjCMethodExpr))) {
+ return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
+ }
+ if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
+ return true;
+ if (Right.is(tok::kw_concept))
+ return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
+ if (Right.is(TT_RequiresClause))
+ return true;
+ if (Left.ClosesTemplateDeclaration) {
+ return Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
+ Right.NewlinesBefore > 0;
+ }
+ if (Left.is(TT_FunctionAnnotationRParen))
+ return true;
+ if (Left.ClosesRequiresClause)
+ return true;
+ if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
+ TT_OverloadedOperator)) {
+ return false;
+ }
+ if (Left.is(TT_RangeBasedForLoopColon))
+ return true;
+ if (Right.is(TT_RangeBasedForLoopColon))
+ return false;
+ if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
+ return true;
+ if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
+ (Left.is(tok::less) && Right.is(tok::less))) {
+ return false;
+ }
+ if (Right.is(TT_BinaryOperator) &&
+ Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
+ (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
+ Right.getPrecedence() != prec::Assignment)) {
+ return true;
+ }
+ if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator, tok::kw_operator))
+ return false;
+ if (Left.is(tok::equal) && Right.isNoneOf(tok::kw_default, tok::kw_delete) &&
+ Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) {
+ return false;
+ }
+ if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
+ Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
+ return false;
+ }
+ if (Left.is(TT_AttributeLParen) ||
+ (Left.is(tok::l_paren) && Left.is(TT_TypeDeclarationParen))) {
+ return false;
+ }
+ if (Left.is(tok::l_paren) && Left.Previous &&
+ (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) {
+ return false;
+ }
+ if (Right.is(TT_ImplicitStringLiteral))
+ return false;
+
+ if (Right.is(tok::r_square) && Right.MatchingParen &&
+ Right.MatchingParen->is(TT_LambdaLSquare)) {
+ return false;
+ }
+
+ // Allow breaking after a trailing annotation, e.g. after a method
+ // declaration.
+ if (Left.is(TT_TrailingAnnotation)) {
+ return Right.isNoneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
+ tok::less, tok::coloncolon);
+ }
+
+ if (Right.isAttribute())
+ return true;
+
+ if (Right.is(TT_AttributeLSquare)) {
+ assert(Left.isNot(tok::l_square));
+ return true;
+ }
+
+ if (Left.is(tok::identifier) && Right.is(tok::string_literal))
+ return true;
+
+ if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
+ return true;
+
+ if (Left.is(TT_CtorInitializerColon)) {
+ return (Style.BreakConstructorInitializers ==
+ FormatStyle::BCIS_AfterColon ||
+ Style.BreakConstructorInitializers ==
+ FormatStyle::BCIS_AfterComma) &&
+ (!Right.isTrailingComment() || Right.NewlinesBefore > 0);
+ }
+ if (Right.is(TT_CtorInitializerColon)) {
+ return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon &&
+ Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterComma;
+ }
+ if (Left.is(TT_CtorInitializerComma) &&
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
+ return false;
+ }
+ if (Right.is(TT_CtorInitializerComma) &&
+ Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
+ return true;
+ }
+ if (Left.is(TT_InheritanceComma) &&
+ Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
+ return false;
+ }
+ if (Right.is(TT_InheritanceComma) &&
+ Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
+ return true;
+ }
+ if (Left.is(TT_ArrayInitializerLSquare))
+ return true;
+ if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
+ return true;
+ if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
+ Left.isNoneOf(tok::arrowstar, tok::lessless) &&
+ Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
+ (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
+ Left.getPrecedence() == prec::Assignment)) {
+ return true;
+ }
+ if (Left.is(TT_AttributeLSquare) && Right.is(tok::l_square)) {
+ assert(Right.isNot(TT_AttributeLSquare));
+ return false;
+ }
+ if (Left.is(tok::r_square) && Right.is(TT_AttributeRSquare)) {
+ assert(Left.isNot(TT_AttributeRSquare));
+ return false;
+ }
+
+ auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
+ if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
+ if (isAllmanLambdaBrace(Left))
+ return !isEmptyLambdaAllowed(Left, ShortLambdaOption);
+ if (isAllmanLambdaBrace(Right))
+ return !isEmptyLambdaAllowed(Right, ShortLambdaOption);
+ }
+
+ if (Right.is(tok::kw_noexcept) && Right.is(TT_TrailingAnnotation)) {
+ switch (Style.AllowBreakBeforeNoexceptSpecifier) {
+ case FormatStyle::BBNSS_Never:
+ return false;
+ case FormatStyle::BBNSS_Always:
+ return true;
+ case FormatStyle::BBNSS_OnlyWithParen:
+ return Right.Next && Right.Next->is(tok::l_paren);
+ }
+ }
+
+ return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
+ tok::kw_class, tok::kw_struct, tok::comment) ||
+ Right.isMemberAccess() ||
+ Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
+ tok::colon, tok::l_square, tok::at) ||
+ (Left.is(tok::r_paren) &&
+ Right.isOneOf(tok::identifier, tok::kw_const)) ||
+ (Left.is(tok::l_paren) && Right.isNot(tok::r_paren)) ||
+ (Left.is(TT_TemplateOpener) && Right.isNot(TT_TemplateCloser));
+}
+
+void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
+ llvm::errs() << "AnnotatedTokens(L=" << Line.Level << ", P=" << Line.PPLevel
+ << ", T=" << Line.Type << ", C=" << Line.IsContinuation
+ << "):\n";
+ const FormatToken *Tok = Line.First;
+ while (Tok) {
+ llvm::errs() << " I=" << Tok->IndentLevel << " M=" << Tok->MustBreakBefore
+ << " C=" << Tok->CanBreakBefore
+ << " T=" << getTokenTypeName(Tok->getType())
+ << " S=" << Tok->SpacesRequiredBefore
+ << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
+ << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
+ << " Name=" << Tok->Tok.getName() << " N=" << Tok->NestingLevel
+ << " L=" << Tok->TotalLength
+ << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
+ for (prec::Level LParen : Tok->FakeLParens)
+ llvm::errs() << LParen << "/";
+ llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
+ llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
+ llvm::errs() << " Text='" << Tok->TokenText << "'\n";
+ if (!Tok->Next)
+ assert(Tok == Line.Last);
+ Tok = Tok->Next;
+ }
+ llvm::errs() << "----\n";
+}
+
+FormatStyle::PointerAlignmentStyle
+TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
+ assert(Reference.isOneOf(tok::amp, tok::ampamp));
+ switch (Style.ReferenceAlignment) {
+ case FormatStyle::RAS_Pointer:
+ return Style.PointerAlignment;
+ case FormatStyle::RAS_Left:
+ return FormatStyle::PAS_Left;
+ case FormatStyle::RAS_Right:
+ return FormatStyle::PAS_Right;
+ case FormatStyle::RAS_Middle:
+ return FormatStyle::PAS_Middle;
+ }
+ assert(0); //"Unhandled value of ReferenceAlignment"
+ return Style.PointerAlignment;
+}
+
+FormatStyle::PointerAlignmentStyle
+TokenAnnotator::getTokenPointerOrReferenceAlignment(
+ const FormatToken &PointerOrReference) const {
+ if (PointerOrReference.isOneOf(tok::amp, tok::ampamp))
+ return getTokenReferenceAlignment(PointerOrReference);
+ assert(PointerOrReference.is(tok::star));
+ return Style.PointerAlignment;
+}
+
+} // namespace format
+} // namespace clang
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 3d55a814e6027..6c4af1d8d0dfa 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1,26177 +1,26267 @@
-//===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "FormatTestBase.h"
-
-#define DEBUG_TYPE "format-test"
-
-namespace clang {
-namespace format {
-namespace test {
-namespace {
-
-class FormatTest : public test::FormatTestBase {};
-
-TEST_F(FormatTest, MessUp) {
- EXPECT_EQ("1 2 3", messUp("1 2 3"));
- EXPECT_EQ("1 2 3", messUp("1\n2\n3"));
- EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
- EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
- EXPECT_EQ("a\n#b c d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
-}
-
-TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
- EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
-}
-
-TEST_F(FormatTest, LLVMStyleOverride) {
- EXPECT_EQ(FormatStyle::LK_Proto,
- getLLVMStyle(FormatStyle::LK_Proto).Language);
-}
-
-//===----------------------------------------------------------------------===//
-// Basic function tests.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { verifyFormat(";"); }
-
-TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
- verifyFormat("int i;", " int i;");
- verifyFormat("\nint i;", " \n\t \v \f int i;");
- verifyFormat("int i;\nint j;", " int i; int j;");
- verifyFormat("int i;\nint j;", " int i;\n int j;");
-
- auto Style = getLLVMStyle();
- Style.KeepEmptyLines.AtStartOfFile = false;
- verifyFormat("int i;", " \n\t \v \f int i;", Style);
-}
-
-TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
- verifyFormat("int i;", "int\ni;");
-}
-
-TEST_F(FormatTest, FormatsNestedBlockStatements) {
- verifyFormat("{\n"
- " {\n"
- " {\n"
- " }\n"
- " }\n"
- "}",
- "{{{}}}");
-}
-
-TEST_F(FormatTest, FormatsNestedCall) {
- verifyFormat("Method(f1, f2(f3));");
- verifyFormat("Method(f1(f2, f3()));");
- verifyFormat("Method(f1(f2, (f3())));");
-}
-
-TEST_F(FormatTest, NestedNameSpecifiers) {
- verifyFormat("vector<::Type> v;");
- verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
- verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
- verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
- verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
- verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
- verifyFormat("bool a = 2 < ::SomeFunction();");
- verifyFormat("ALWAYS_INLINE ::std::string getName();");
- verifyFormat("some::string getName();");
-}
-
-TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
- verifyFormat("if (a) {\n"
- " f();\n"
- "}",
- "if(a){f();}");
- EXPECT_EQ(4, ReplacementCount);
- verifyNoChange("if (a) {\n"
- " f();\n"
- "}");
- EXPECT_EQ(0, ReplacementCount);
- verifyNoChange("/*\r\n"
- "\r\n"
- "*/");
- EXPECT_EQ(0, ReplacementCount);
-}
-
-TEST_F(FormatTest, RemovesEmptyLines) {
- verifyFormat("class C {\n"
- " int i;\n"
- "};",
- "class C {\n"
- " int i;\n"
- "\n"
- "};");
-
- // Don't remove empty lines at the start of namespaces or extern "C" blocks.
- verifyFormat("namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- "namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
- verifyFormat("/* something */ namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- "/* something */ namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
- verifyFormat("inline namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- "inline namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
- verifyFormat("/* something */ inline namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- "/* something */ inline namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
- verifyFormat("export namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- "export namespace N {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
- verifyFormat("extern /**/ \"C\" /**/ {\n"
- "\n"
- "int i;\n"
- "}",
- "extern /**/ \"C\" /**/ {\n"
- "\n"
- "int i;\n"
- "}",
- getGoogleStyle());
-
- auto CustomStyle = getLLVMStyle();
- CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
- CustomStyle.BraceWrapping.AfterNamespace = true;
- CustomStyle.KeepEmptyLines.AtStartOfBlock = false;
- verifyFormat("namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- "namespace N\n"
- "{\n"
- "\n"
- "\n"
- "int i;\n"
- "}",
- CustomStyle);
- verifyFormat("/* something */ namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- "/* something */ namespace N {\n"
- "\n"
- "\n"
- "int i;\n"
- "}",
- CustomStyle);
- verifyFormat("inline namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- "inline namespace N\n"
- "{\n"
- "\n"
- "\n"
- "int i;\n"
- "}",
- CustomStyle);
- verifyFormat("/* something */ inline namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- "/* something */ inline namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- CustomStyle);
- verifyFormat("export namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- "export namespace N\n"
- "{\n"
- "\n"
- "int i;\n"
- "}",
- CustomStyle);
- verifyFormat("namespace a\n"
- "{\n"
- "namespace b\n"
- "{\n"
- "\n"
- "class AA {};\n"
- "\n"
- "} // namespace b\n"
- "} // namespace a",
- "namespace a\n"
- "{\n"
- "namespace b\n"
- "{\n"
- "\n"
- "\n"
- "class AA {};\n"
- "\n"
- "\n"
- "}\n"
- "}",
- CustomStyle);
- verifyFormat("namespace A /* comment */\n"
- "{\n"
- "class B {}\n"
- "} // namespace A",
- "namespace A /* comment */ { class B {} }", CustomStyle);
- verifyFormat("namespace A\n"
- "{ /* comment */\n"
- "class B {}\n"
- "} // namespace A",
- "namespace A {/* comment */ class B {} }", CustomStyle);
- verifyFormat("namespace A\n"
- "{ /* comment */\n"
- "\n"
- "class B {}\n"
- "\n"
- ""
- "} // namespace A",
- "namespace A { /* comment */\n"
- "\n"
- "\n"
- "class B {}\n"
- "\n"
- "\n"
- "}",
- CustomStyle);
- verifyFormat("namespace A /* comment */\n"
- "{\n"
- "\n"
- "class B {}\n"
- "\n"
- "} // namespace A",
- "namespace A/* comment */ {\n"
- "\n"
- "\n"
- "class B {}\n"
- "\n"
- "\n"
- "}",
- CustomStyle);
-
- // ...but do keep inlining and removing empty lines for non-block extern "C"
- // functions.
- verifyGoogleFormat("extern \"C\" int f() { return 42; }");
- verifyFormat("extern \"C\" int f() {\n"
- " int i = 42;\n"
- " return i;\n"
- "}",
- "extern \"C\" int f() {\n"
- "\n"
- " int i = 42;\n"
- " return i;\n"
- "}",
- getGoogleStyle());
-
- // Remove empty lines at the beginning and end of blocks.
- verifyFormat("void f() {\n"
- "\n"
- " if (a) {\n"
- "\n"
- " f();\n"
- " }\n"
- "}",
- "void f() {\n"
- "\n"
- " if (a) {\n"
- "\n"
- " f();\n"
- "\n"
- " }\n"
- "\n"
- "}");
- verifyFormat("void f() {\n"
- " if (a) {\n"
- " f();\n"
- " }\n"
- "}",
- "void f() {\n"
- "\n"
- " if (a) {\n"
- "\n"
- " f();\n"
- "\n"
- " }\n"
- "\n"
- "}",
- getGoogleStyle());
-
- // Don't remove empty lines in more complex control statements.
- verifyFormat("void f() {\n"
- " if (a) {\n"
- " f();\n"
- "\n"
- " } else if (b) {\n"
- " f();\n"
- " }\n"
- "}",
- "void f() {\n"
- " if (a) {\n"
- " f();\n"
- "\n"
- " } else if (b) {\n"
- " f();\n"
- "\n"
- " }\n"
- "\n"
- "}");
-
- // Don't remove empty lines before namespace endings.
- FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
- LLVMWithNoNamespaceFix.FixNamespaceComments = false;
- verifyNoChange("namespace {\n"
- "int i;\n"
- "\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace {\n"
- "int i;\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyNoChange("namespace {\n"
- "int i;\n"
- "\n"
- "};",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace {\n"
- "int i;\n"
- "};",
- LLVMWithNoNamespaceFix);
- verifyNoChange("namespace {\n"
- "int i;\n"
- "\n"
- "}");
- verifyFormat("namespace {\n"
- "int i;\n"
- "\n"
- "} // namespace",
- "namespace {\n"
- "int i;\n"
- "\n"
- "} // namespace");
-
- FormatStyle Style = getLLVMStyle();
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- Style.MaxEmptyLinesToKeep = 2;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- Style.BraceWrapping.AfterFunction = true;
- Style.KeepEmptyLines.AtStartOfBlock = false;
-
- verifyFormat("class Foo\n"
- "{\n"
- " Foo() {}\n"
- "\n"
- " void funk() {}\n"
- "};",
- "class Foo\n"
- "{\n"
- " Foo()\n"
- " {\n"
- " }\n"
- "\n"
- " void funk() {}\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
- verifyFormat("x = (a) and (b);");
- verifyFormat("x = (a) or (b);");
- verifyFormat("x = (a) bitand (b);");
- verifyFormat("x = (a) bitor (b);");
- verifyFormat("x = (a) not_eq (b);");
- verifyFormat("x = (a) and_eq (b);");
- verifyFormat("x = (a) or_eq (b);");
- verifyFormat("x = (a) xor (b);");
-}
-
-TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
- verifyFormat("x = compl(a);");
- verifyFormat("x = not(a);");
- verifyFormat("x = bitand(a);");
- // Unary operator must not be merged with the next identifier
- verifyFormat("x = compl a;");
- verifyFormat("x = not a;");
- verifyFormat("x = bitand a;");
-}
-
-//===----------------------------------------------------------------------===//
-// Tests for control statements.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
- verifyFormat("if (true)\n f();\ng();");
- verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();");
- verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
- verifyFormat("if constexpr (true)\n"
- " f();\ng();");
- verifyFormat("if CONSTEXPR (true)\n"
- " f();\ng();");
- verifyFormat("if constexpr (a)\n"
- " if constexpr (b)\n"
- " if constexpr (c)\n"
- " g();\n"
- "h();");
- verifyFormat("if CONSTEXPR (a)\n"
- " if CONSTEXPR (b)\n"
- " if CONSTEXPR (c)\n"
- " g();\n"
- "h();");
- verifyFormat("if constexpr (a)\n"
- " if constexpr (b) {\n"
- " f();\n"
- " }\n"
- "g();");
- verifyFormat("if CONSTEXPR (a)\n"
- " if CONSTEXPR (b) {\n"
- " f();\n"
- " }\n"
- "g();");
-
- verifyFormat("if consteval {\n}");
- verifyFormat("if !consteval {\n}");
- verifyFormat("if not consteval {\n}");
- verifyFormat("if consteval {\n} else {\n}");
- verifyFormat("if !consteval {\n} else {\n}");
- verifyFormat("if consteval {\n"
- " f();\n"
- "}");
- verifyFormat("if !consteval {\n"
- " f();\n"
- "}");
- verifyFormat("if consteval {\n"
- " f();\n"
- "} else {\n"
- " g();\n"
- "}");
- verifyFormat("if CONSTEVAL {\n"
- " f();\n"
- "}");
- verifyFormat("if !CONSTEVAL {\n"
- " f();\n"
- "}");
-
- verifyFormat("if (a)\n"
- " g();");
- verifyFormat("if (a) {\n"
- " g()\n"
- "};");
- verifyFormat("if (a)\n"
- " g();\n"
- "else\n"
- " g();");
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else\n"
- " g();");
- verifyFormat("if (a)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}");
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}");
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " g();");
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b)\n"
- " g();\n"
- "else\n"
- " g();");
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else\n"
- " g();");
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}");
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}");
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}");
-
- FormatStyle AllowsMergedIf = getLLVMStyle();
- AllowsMergedIf.IfMacros.push_back("MYIF");
- AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- verifyFormat("if (a)\n"
- " // comment\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("{\n"
- " if (a)\n"
- " label:\n"
- " f();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("#define A \\\n"
- " if (a) \\\n"
- " label: \\\n"
- " f()",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " ;",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " if (b) return;",
- AllowsMergedIf);
-
- verifyFormat("if (a) // Can't merge this\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("if (a) /* still don't merge */\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("if (a) { // Never merge this\n"
- " f();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) { /* Never merge this */\n"
- " f();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " // comment\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("{\n"
- " MYIF (a)\n"
- " label:\n"
- " f();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("#define A \\\n"
- " MYIF (a) \\\n"
- " label: \\\n"
- " f()",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " ;",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " MYIF (b) return;",
- AllowsMergedIf);
-
- verifyFormat("MYIF (a) // Can't merge this\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) /* still don't merge */\n"
- " f();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) { // Never merge this\n"
- " f();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) { /* Never merge this */\n"
- " f();\n"
- "}",
- AllowsMergedIf);
-
- AllowsMergedIf.ColumnLimit = 14;
- // Where line-lengths matter, a 2-letter synonym that maintains line length.
- // Not IF to avoid any confusion that IF is somehow special.
- AllowsMergedIf.IfMacros.push_back("FI");
- verifyFormat("if (a) return;", AllowsMergedIf);
- verifyFormat("if (aaaaaaaaa)\n"
- " return;",
- AllowsMergedIf);
- verifyFormat("FI (a) return;", AllowsMergedIf);
- verifyFormat("FI (aaaaaaaaa)\n"
- " return;",
- AllowsMergedIf);
-
- AllowsMergedIf.ColumnLimit = 13;
- verifyFormat("if (a)\n return;", AllowsMergedIf);
- verifyFormat("FI (a)\n return;", AllowsMergedIf);
-
- FormatStyle AllowsMergedIfElse = getLLVMStyle();
- AllowsMergedIfElse.IfMacros.push_back("MYIF");
- AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_AllIfsAndElse;
- verifyFormat("if (a)\n"
- " // comment\n"
- " f();\n"
- "else\n"
- " // comment\n"
- " f();",
- AllowsMergedIfElse);
- verifyFormat("{\n"
- " if (a)\n"
- " label:\n"
- " f();\n"
- " else\n"
- " label:\n"
- " f();\n"
- "}",
- AllowsMergedIfElse);
- verifyFormat("if (a)\n"
- " ;\n"
- "else\n"
- " ;",
- AllowsMergedIfElse);
- verifyFormat("if (a) {\n"
- "} else {\n"
- "}",
- AllowsMergedIfElse);
- verifyFormat("if (a) return;\n"
- "else if (b) return;\n"
- "else return;",
- AllowsMergedIfElse);
- verifyFormat("if (a) {\n"
- "} else return;",
- AllowsMergedIfElse);
- verifyFormat("if (a) {\n"
- "} else if (b) return;\n"
- "else return;",
- AllowsMergedIfElse);
- verifyFormat("if (a) return;\n"
- "else if (b) {\n"
- "} else return;",
- AllowsMergedIfElse);
- verifyFormat("if (a)\n"
- " if (b) return;\n"
- " else return;",
- AllowsMergedIfElse);
- verifyFormat("if constexpr (a)\n"
- " if constexpr (b) return;\n"
- " else if constexpr (c) return;\n"
- " else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a)\n"
- " // comment\n"
- " f();\n"
- "else\n"
- " // comment\n"
- " f();",
- AllowsMergedIfElse);
- verifyFormat("{\n"
- " MYIF (a)\n"
- " label:\n"
- " f();\n"
- " else\n"
- " label:\n"
- " f();\n"
- "}",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a)\n"
- " ;\n"
- "else\n"
- " ;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a) {\n"
- "} else {\n"
- "}",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a) return;\n"
- "else MYIF (b) return;\n"
- "else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a) {\n"
- "} else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a) {\n"
- "} else MYIF (b) return;\n"
- "else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a) return;\n"
- "else MYIF (b) {\n"
- "} else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF (a)\n"
- " MYIF (b) return;\n"
- " else return;",
- AllowsMergedIfElse);
- verifyFormat("MYIF constexpr (a)\n"
- " MYIF constexpr (b) return;\n"
- " else MYIF constexpr (c) return;\n"
- " else return;",
- AllowsMergedIfElse);
-}
-
-TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
- FormatStyle AllowsMergedIf = getLLVMStyle();
- AllowsMergedIf.IfMacros.push_back("MYIF");
- AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- verifyFormat("if (a)\n"
- " f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " f();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
-
- verifyFormat("if (a) g();", AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " f();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
-
- verifyFormat("MYIF (a) g();", AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else MYIF (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else MYIF (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else if (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a)\n"
- " g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_OnlyFirstIf;
-
- verifyFormat("if (a) f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) f();\n"
- "else {\n"
- " if (a) f();\n"
- " else {\n"
- " g();\n"
- " }\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- verifyFormat("if (a) g();", AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) f();\n"
- "else {\n"
- " if (a) f();\n"
- " else {\n"
- " g();\n"
- " }\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- verifyFormat("MYIF (a) g();", AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b)\n"
- " g();\n"
- "else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else\n"
- " g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b)\n"
- " g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_AllIfsAndElse;
-
- verifyFormat("if (a) f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) f();\n"
- "else {\n"
- " if (a) f();\n"
- " else {\n"
- " g();\n"
- " }\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- verifyFormat("if (a) g();", AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else g();",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("if (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) f();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) f();\n"
- "else {\n"
- " if (a) f();\n"
- " else {\n"
- " g();\n"
- " }\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-
- verifyFormat("MYIF (a) g();", AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g()\n"
- "};",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b) g();\n"
- "else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else g();",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) g();\n"
- "else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) g();\n"
- "else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else MYIF (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
- verifyFormat("MYIF (a) {\n"
- " g();\n"
- "} else if (b) {\n"
- " g();\n"
- "} else {\n"
- " g();\n"
- "}",
- AllowsMergedIf);
-}
-
-TEST_F(FormatTest, WrapMultipleStatementIfAndElseBraces) {
- auto Style = getLLVMStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_AllIfsAndElse;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- Style.BraceWrapping.BeforeElse = true;
-
- verifyFormat("if (x)\n"
- "{\n"
- " ++x;\n"
- " --y;\n"
- "}\n"
- "else\n"
- "{\n"
- " --x;\n"
- " ++y;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
- verifyFormat("while (true)\n"
- " ;");
- verifyFormat("for (;;)\n"
- " ;");
-
- FormatStyle AllowsMergedLoops = getLLVMStyle();
- AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
-
- verifyFormat("while (true) continue;", AllowsMergedLoops);
- verifyFormat("for (;;) continue;", AllowsMergedLoops);
- verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
- verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
- verifyFormat("while (true);", AllowsMergedLoops);
- verifyFormat("for (;;);", AllowsMergedLoops);
- verifyFormat("for (;;)\n"
- " for (;;) continue;",
- AllowsMergedLoops);
- verifyFormat("for (;;)\n"
- " while (true) continue;",
- AllowsMergedLoops);
- verifyFormat("while (true)\n"
- " for (;;) continue;",
- AllowsMergedLoops);
- verifyFormat("BOOST_FOREACH (int &v, vec)\n"
- " for (;;) continue;",
- AllowsMergedLoops);
- verifyFormat("for (;;)\n"
- " BOOST_FOREACH (int &v, vec) continue;",
- AllowsMergedLoops);
- verifyFormat("for (;;) // Can't merge this\n"
- " continue;",
- AllowsMergedLoops);
- verifyFormat("for (;;) /* still don't merge */\n"
- " continue;",
- AllowsMergedLoops);
- verifyFormat("do a++;\n"
- "while (true);",
- AllowsMergedLoops);
- verifyFormat("do /* Don't merge */\n"
- " a++;\n"
- "while (true);",
- AllowsMergedLoops);
- verifyFormat("do // Don't merge\n"
- " a++;\n"
- "while (true);",
- AllowsMergedLoops);
- verifyFormat("do\n"
- " // Don't merge\n"
- " a++;\n"
- "while (true);",
- AllowsMergedLoops);
-
- // Without braces labels are interpreted differently.
- verifyFormat("{\n"
- " do\n"
- " label:\n"
- " a++;\n"
- " while (true);\n"
- "}",
- AllowsMergedLoops);
-
- // Don't merge if there are comments before the null statement.
- verifyFormat("while (1) //\n"
- " ;",
- AllowsMergedLoops);
- verifyFormat("for (;;) /**/\n"
- " ;",
- AllowsMergedLoops);
- verifyFormat("while (true) /**/\n"
- " ;",
- "while (true) /**/;", AllowsMergedLoops);
-}
-
-TEST_F(FormatTest, FormatShortBracedStatements) {
- FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
- EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
- EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
- FormatStyle::SIS_Never);
- EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
- EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
- verifyFormat("for (;;) {\n"
- " f();\n"
- "}");
- verifyFormat("/*comment*/ for (;;) {\n"
- " f();\n"
- "}");
- verifyFormat("BOOST_FOREACH (int v, vec) {\n"
- " f();\n"
- "}");
- verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
- " f();\n"
- "}");
- verifyFormat("while (true) {\n"
- " f();\n"
- "}");
- verifyFormat("/*comment*/ while (true) {\n"
- " f();\n"
- "}");
- verifyFormat("if (true) {\n"
- " f();\n"
- "}");
- verifyFormat("/*comment*/ if (true) {\n"
- " f();\n"
- "}");
-
- AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
- FormatStyle::SBS_Empty;
- AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- verifyFormat("if (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if (i) break;", AllowSimpleBracedStatements);
- verifyFormat("if (i > 0) {\n"
- " return i;\n"
- "}",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
- // Where line-lengths matter, a 2-letter synonym that maintains line length.
- // Not IF to avoid any confusion that IF is somehow special.
- AllowSimpleBracedStatements.IfMacros.push_back("FI");
- AllowSimpleBracedStatements.ColumnLimit = 40;
- AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
- FormatStyle::SBS_Always;
- AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
- AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
- AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
- AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
-
- verifyFormat("if (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if consteval {}", AllowSimpleBracedStatements);
- verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
- verifyFormat("while (true) {}", AllowSimpleBracedStatements);
- verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
- verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
- verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if (true) { fffffffffffffffffffffff(); }",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " ffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) { //\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " f();\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " f();\n"
- "} else {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " ffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) { //\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " f();\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " f();\n"
- "} else {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- verifyFormat("struct A2 {\n"
- " int X;\n"
- "};",
- AllowSimpleBracedStatements);
- verifyFormat("typedef struct A2 {\n"
- " int X;\n"
- "} A2_t;",
- AllowSimpleBracedStatements);
- verifyFormat("template <int> struct A2 {\n"
- " struct B {};\n"
- "};",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_Never;
- verifyFormat("if (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true) {\n"
- " f();\n"
- "} else {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {\n"
- " f();\n"
- "} else {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
- verifyFormat("while (true) {}", AllowSimpleBracedStatements);
- verifyFormat("while (true) {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
- verifyFormat("for (;;) {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
- verifyFormat("BOOST_FOREACH (int v, vec) {\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
- AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
- FormatStyle::BWACS_Always;
-
- verifyFormat("if (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
- verifyFormat("while (true) {}", AllowSimpleBracedStatements);
- verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
- verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
- verifyFormat("if (true) { fffffffffffffffffffffff(); }",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " ffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{ //\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " f();\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " f();\n"
- "} else\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " ffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{ //\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " f();\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " f();\n"
- "} else\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_Never;
- verifyFormat("if (true) {}", AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("if (true)\n"
- "{\n"
- " f();\n"
- "} else\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("MYIF (true)\n"
- "{\n"
- " f();\n"
- "} else\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
- verifyFormat("while (true) {}", AllowSimpleBracedStatements);
- verifyFormat("while (true)\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
- verifyFormat("for (;;)\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
- verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
- verifyFormat("BOOST_FOREACH (int v, vec)\n"
- "{\n"
- " f();\n"
- "}",
- AllowSimpleBracedStatements);
-
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
-
- verifyFormat("while (i > 0)\n"
- "{\n"
- " --i;\n"
- "}",
- Style);
-
- verifyFormat("if (a)\n"
- "{\n"
- " ++b;\n"
- "}",
- Style);
-
- verifyFormat("if (a)\n"
- "{\n"
- " b = 1;\n"
- "} else\n"
- "{\n"
- " b = 0;\n"
- "}",
- Style);
-
- verifyFormat("if (a)\n"
- "{\n"
- " b = 1;\n"
- "} else if (c)\n"
- "{\n"
- " b = 2;\n"
- "} else\n"
- "{\n"
- " b = 0;\n"
- "}",
- Style);
-
- Style.BraceWrapping.BeforeElse = true;
-
- verifyFormat("if (a)\n"
- "{\n"
- " b = 1;\n"
- "}\n"
- "else\n"
- "{\n"
- " b = 0;\n"
- "}",
- Style);
-
- verifyFormat("if (a)\n"
- "{\n"
- " b = 1;\n"
- "}\n"
- "else if (c)\n"
- "{\n"
- " b = 2;\n"
- "}\n"
- "else\n"
- "{\n"
- " b = 0;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandsMacros) {
- verifyFormat("#define A (parentheses)");
- verifyFormat("/* comment */ #define A (parentheses)");
- verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
- // Even the partial code should never be merged.
- verifyNoChange("/* comment */ #define A (parentheses)\n"
- "#");
- verifyFormat("/* comment */ #define A (parentheses)\n"
- "#\n");
- verifyFormat("/* comment */ #define A (parentheses)\n"
- "#define B (parentheses)");
- verifyFormat("#define true ((int)1)");
- verifyFormat("#define and(x)");
- verifyFormat("#define if(x) x");
- verifyFormat("#define return(x) (x)");
- verifyFormat("#define while(x) for (; x;)");
- verifyFormat("#define xor(x) (^(x))");
- verifyFormat("#define __except(x)");
- verifyFormat("#define __try(x)");
-
- // https://llvm.org/PR54348.
- verifyFormat(
- "#define A"
- " "
- "\\\n"
- " class & {}");
-
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- // Test that a macro definition never gets merged with the following
- // definition.
- // FIXME: The AAA macro definition probably should not be split into 3 lines.
- verifyFormat("#define AAA "
- " \\\n"
- " N "
- " \\\n"
- " {\n"
- "#define BBB }",
- Style);
- // verifyFormat("#define AAA N { //", Style);
-
- verifyFormat("MACRO(return)");
- verifyFormat("MACRO(co_await)");
- verifyFormat("MACRO(co_return)");
- verifyFormat("MACRO(co_yield)");
- verifyFormat("MACRO(return, something)");
- verifyFormat("MACRO(co_return, something)");
- verifyFormat("MACRO(something##something)");
- verifyFormat("MACRO(return##something)");
- verifyFormat("MACRO(co_return##something)");
-
- verifyFormat("#define A x:");
-
- verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
- " { \\\n"
- " #Bar \\\n"
- " }");
- verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
- " { #Bar }");
-}
-
-TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
- FormatStyle Style = getLLVMStyleWithColumns(60);
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
- Style.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("#define A \\\n"
- " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
- " { \\\n"
- " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
- " }\n"
- "X;",
- "#define A \\\n"
- " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
- " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
- " }\n"
- "X;",
- Style);
-}
-
-TEST_F(FormatTest, ParseIfElse) {
- verifyFormat("if (true)\n"
- " if (true)\n"
- " if (true)\n"
- " f();\n"
- " else\n"
- " g();\n"
- " else\n"
- " h();\n"
- "else\n"
- " i();");
- verifyFormat("if (true)\n"
- " if (true)\n"
- " if (true) {\n"
- " if (true)\n"
- " f();\n"
- " } else {\n"
- " g();\n"
- " }\n"
- " else\n"
- " h();\n"
- "else {\n"
- " i();\n"
- "}");
- verifyFormat("if (true)\n"
- " if constexpr (true)\n"
- " if (true) {\n"
- " if constexpr (true)\n"
- " f();\n"
- " } else {\n"
- " g();\n"
- " }\n"
- " else\n"
- " h();\n"
- "else {\n"
- " i();\n"
- "}");
- verifyFormat("if (true)\n"
- " if CONSTEXPR (true)\n"
- " if (true) {\n"
- " if CONSTEXPR (true)\n"
- " f();\n"
- " } else {\n"
- " g();\n"
- " }\n"
- " else\n"
- " h();\n"
- "else {\n"
- " i();\n"
- "}");
- verifyFormat("void f() {\n"
- " if (a) {\n"
- " } else {\n"
- " }\n"
- "}");
-}
-
-TEST_F(FormatTest, ElseIf) {
- verifyFormat("if (a) {\n} else if (b) {\n}");
- verifyFormat("if (a)\n"
- " f();\n"
- "else if (b)\n"
- " g();\n"
- "else\n"
- " h();");
- verifyFormat("if (a)\n"
- " f();\n"
- "else // comment\n"
- " if (b) {\n"
- " g();\n"
- " h();\n"
- " }");
- verifyFormat("if constexpr (a)\n"
- " f();\n"
- "else if constexpr (b)\n"
- " g();\n"
- "else\n"
- " h();");
- verifyFormat("if CONSTEXPR (a)\n"
- " f();\n"
- "else if CONSTEXPR (b)\n"
- " g();\n"
- "else\n"
- " h();");
- verifyFormat("if (a) {\n"
- " f();\n"
- "}\n"
- "// or else ..\n"
- "else {\n"
- " g()\n"
- "}");
-
- verifyFormat("if (a) {\n"
- "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
- "}");
- verifyFormat("if (a) {\n"
- "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
- "}");
- verifyFormat("if (a) {\n"
- "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
- "}");
- verifyFormat("if (a) {\n"
- "} else if (\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
- "}",
- getLLVMStyleWithColumns(62));
- verifyFormat("if (a) {\n"
- "} else if constexpr (\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
- "}",
- getLLVMStyleWithColumns(62));
- verifyFormat("if (a) {\n"
- "} else if CONSTEXPR (\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
- "}",
- getLLVMStyleWithColumns(62));
-}
-
-TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
- EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
- verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
- verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
- verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
- verifyFormat("int *f1(int &a) const &;", Style);
- verifyFormat("int *f1(int &a) const & = 0;", Style);
- verifyFormat("int *a = f1();", Style);
- verifyFormat("int &b = f2();", Style);
- verifyFormat("int &&c = f3();", Style);
- verifyFormat("int f3() { return sizeof(Foo &); }", Style);
- verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
- verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
- verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
- verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
- verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
- verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
- verifyFormat(
- "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
- " res2 = [](int &a) { return 0000000000000; };",
- Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
- verifyFormat("Const unsigned int *c;\n"
- "const unsigned int *d;\n"
- "Const unsigned int &e;\n"
- "const unsigned int &f;\n"
- "int *f1(int *a, int &b, int &&c);\n"
- "double *(*f2)(int *a, double &&b);\n"
- "const unsigned &&g;\n"
- "Const unsigned h;",
- Style);
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
- verifyFormat("Const unsigned int *c;\n"
- "const unsigned int *d;\n"
- "Const unsigned int &e;\n"
- "const unsigned int &f;\n"
- "int *f1(int *a, int &b, int &&c);\n"
- "double *(*f2)(int *a, double &&b);\n"
- "const unsigned &&g;\n"
- "Const unsigned h;",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
- verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
- verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
- verifyFormat("int* f1(int& a) const& = 0;", Style);
- verifyFormat("int* a = f1();", Style);
- verifyFormat("int& b = f2();", Style);
- verifyFormat("int&& c = f3();", Style);
- verifyFormat("int f3() { return sizeof(Foo&); }", Style);
- verifyFormat("int f4() { return sizeof(Foo&&); }", Style);
- verifyFormat("void f5() { int f6(Foo&, Bar&); }", Style);
- verifyFormat("void f5() { int f6(Foo&&, Bar&&); }", Style);
- verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
- verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
- verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
- verifyFormat(
- "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
- " res2 = [](int& a) { return 0000000000000; };",
- Style);
- verifyFormat("[](decltype(foo)& Bar) {}", Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
- verifyFormat("Const unsigned int* c;\n"
- "const unsigned int* d;\n"
- "Const unsigned int& e;\n"
- "const unsigned int& f;\n"
- "int* f1(int* a, int& b, int&& c);\n"
- "double* (*f2)(int* a, double&& b);\n"
- "const unsigned&& g;\n"
- "Const unsigned h;",
- Style);
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
- verifyFormat("Const unsigned int* c;\n"
- "const unsigned int* d;\n"
- "Const unsigned int& e;\n"
- "const unsigned int& f;\n"
- "int* f1(int* a, int& b, int&& c);\n"
- "double* (*f2)(int* a, double&& b);\n"
- "const unsigned&& g;\n"
- "Const unsigned h;",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Right;
- Style.ReferenceAlignment = FormatStyle::RAS_Left;
- verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
- verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
- verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
- verifyFormat("int *a = f1();", Style);
- verifyFormat("int& b = f2();", Style);
- verifyFormat("int&& c = f3();", Style);
- verifyFormat("int f3() { return sizeof(Foo&); }", Style);
- verifyFormat("int f4() { return sizeof(Foo&&); }", Style);
- verifyFormat("void f5() { int f6(Foo&, Bar&); }", Style);
- verifyFormat("void f5() { int f6(Foo&&, Bar&&); }", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
- verifyFormat("Const unsigned int *c;\n"
- "const unsigned int *d;\n"
- "Const unsigned int& e;\n"
- "const unsigned int& f;\n"
- "int *f1(int *a, int& b, int&& c);\n"
- "double *(*f2)(int *a, double&& b);\n"
- "const unsigned&& g;\n"
- "Const unsigned h;",
- Style);
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
- verifyFormat("Const unsigned int *c;\n"
- "const unsigned int *d;\n"
- "Const unsigned int& e;\n"
- "const unsigned int& f;\n"
- "int *f1(int *a, int& b, int&& c);\n"
- "double *(*f2)(int *a, double&& b);\n"
- "const unsigned&& g;\n"
- "Const unsigned h;",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- Style.ReferenceAlignment = FormatStyle::RAS_Middle;
- verifyFormat("int* f1(int* a, int & b, int && c);", Style);
- verifyFormat("int & f2(int && c, int* a, int & b);", Style);
- verifyFormat("int && f3(int & b, int && c, int* a);", Style);
- verifyFormat("int* a = f1();", Style);
- verifyFormat("int & b = f2();", Style);
- verifyFormat("int && c = f3();", Style);
- verifyFormat("int f3() { return sizeof(Foo &); }", Style);
- verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
- verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
- verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
- verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
- verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
- verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
- verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
- verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
- verifyFormat(
- "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
- " res2 = [](int & a) { return 0000000000000; };",
- Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
- verifyFormat("Const unsigned int* c;\n"
- "const unsigned int* d;\n"
- "Const unsigned int & e;\n"
- "const unsigned int & f;\n"
- "int* f1(int* a, int & b, int && c);\n"
- "double* (*f2)(int* a, double && b);\n"
- "const unsigned && g;\n"
- "Const unsigned h;",
- Style);
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
- verifyFormat("Const unsigned int* c;\n"
- "const unsigned int* d;\n"
- "Const unsigned int & e;\n"
- "const unsigned int & f;\n"
- "int* f1(int* a, int & b, int && c);\n"
- "double* (*f2)(int* a, double && b);\n"
- "const unsigned && g;\n"
- "Const unsigned h;",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- Style.ReferenceAlignment = FormatStyle::RAS_Right;
- verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
- verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
- verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
- verifyFormat("int * a = f1();", Style);
- verifyFormat("int &b = f2();", Style);
- verifyFormat("int &&c = f3();", Style);
- verifyFormat("int f3() { return sizeof(Foo &); }", Style);
- verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
- verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
- verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
- verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
- verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
- verifyFormat("Const unsigned int * c;\n"
- "const unsigned int * d;\n"
- "Const unsigned int &e;\n"
- "const unsigned int &f;\n"
- "int * f1(int * a, int &b, int &&c);\n"
- "double * (*f2)(int * a, double &&b);\n"
- "const unsigned &&g;\n"
- "Const unsigned h;",
- Style);
- Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
- verifyFormat("Const unsigned int * c;\n"
- "const unsigned int * d;\n"
- "Const unsigned int &e;\n"
- "const unsigned int &f;\n"
- "int * f1(int * a, int &b, int &&c);\n"
- "double * (*f2)(int * a, double &&b);\n"
- "const unsigned &&g;\n"
- "Const unsigned h;",
- Style);
-
- // FIXME: we don't handle this yet, so output may be arbitrary until it's
- // specifically handled
- // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
-}
-
-TEST_F(FormatTest, FormatsForLoop) {
- verifyFormat(
- "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
- " ++VeryVeryLongLoopVariable)\n"
- " ;");
- verifyFormat("for (;;)\n"
- " f();");
- verifyFormat("for (;;) {\n}");
- verifyFormat("for (;;) {\n"
- " f();\n"
- "}");
- verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
-
- verifyFormat(
- "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
- " E = UnwrappedLines.end();\n"
- " I != E; ++I) {\n}");
-
- verifyFormat(
- "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
- " ++IIIII) {\n}");
- verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
- " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
- verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
- " I = FD->getDeclsInPrototypeScope().begin(),\n"
- " E = FD->getDeclsInPrototypeScope().end();\n"
- " I != E; ++I) {\n}");
- verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
- " I = Container.begin(),\n"
- " E = Container.end();\n"
- " I != E; ++I) {\n}",
- getLLVMStyleWithColumns(76));
-
- verifyFormat(
- "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
- " ++aaaaaaaaaaa) {\n}");
- verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
- " ++i) {\n}");
- verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
- " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
- "}");
- verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
- " aaaaaaaaaa);\n"
- " iter; ++iter) {\n"
- "}");
- verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
- " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
-
- // These should not be formatted as Objective-C for-in loops.
- verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
- verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
- verifyFormat("Foo *x;\nfor (x in y) {\n}");
- verifyFormat(
- "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
-
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("for (int aaaaaaaaaaa = 1;\n"
- " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa);\n"
- " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
- "}",
- NoBinPacking);
- verifyFormat(
- "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
- " E = UnwrappedLines.end();\n"
- " I != E;\n"
- " ++I) {\n}",
- NoBinPacking);
-
- FormatStyle AlignLeft = getLLVMStyle();
- AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
-}
-
-TEST_F(FormatTest, RangeBasedForLoops) {
- verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
- verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
- verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
- verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
-}
-
-TEST_F(FormatTest, ForEachLoops) {
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
- EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
- verifyFormat("void f() {\n"
- " for (;;) {\n"
- " }\n"
- " foreach (Item *item, itemlist) {\n"
- " }\n"
- " Q_FOREACH (Item *item, itemlist) {\n"
- " }\n"
- " BOOST_FOREACH (Item *item, itemlist) {\n"
- " }\n"
- " UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
- "}",
- Style);
- verifyFormat("void f() {\n"
- " for (;;)\n"
- " int j = 1;\n"
- " Q_FOREACH (int v, vec)\n"
- " v *= 2;\n"
- " for (;;) {\n"
- " int j = 1;\n"
- " }\n"
- " Q_FOREACH (int v, vec) {\n"
- " v *= 2;\n"
- " }\n"
- "}",
- Style);
-
- FormatStyle ShortBlocks = getLLVMStyle();
- ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
- verifyFormat("void f() {\n"
- " for (;;)\n"
- " int j = 1;\n"
- " Q_FOREACH (int &v, vec)\n"
- " v *= 2;\n"
- " for (;;) {\n"
- " int j = 1;\n"
- " }\n"
- " Q_FOREACH (int &v, vec) {\n"
- " int j = 1;\n"
- " }\n"
- "}",
- ShortBlocks);
-
- FormatStyle ShortLoops = getLLVMStyle();
- ShortLoops.AllowShortLoopsOnASingleLine = true;
- EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
- verifyFormat("void f() {\n"
- " for (;;) int j = 1;\n"
- " Q_FOREACH (int &v, vec) int j = 1;\n"
- " for (;;) {\n"
- " int j = 1;\n"
- " }\n"
- " Q_FOREACH (int &v, vec) {\n"
- " int j = 1;\n"
- " }\n"
- "}",
- ShortLoops);
-
- FormatStyle ShortBlocksAndLoops = getLLVMStyle();
- ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
- verifyFormat("void f() {\n"
- " for (;;) int j = 1;\n"
- " Q_FOREACH (int &v, vec) int j = 1;\n"
- " for (;;) { int j = 1; }\n"
- " Q_FOREACH (int &v, vec) { int j = 1; }\n"
- "}",
- ShortBlocksAndLoops);
-
- Style.SpaceBeforeParens =
- FormatStyle::SBPO_ControlStatementsExceptControlMacros;
- verifyFormat("void f() {\n"
- " for (;;) {\n"
- " }\n"
- " foreach(Item *item, itemlist) {\n"
- " }\n"
- " Q_FOREACH(Item *item, itemlist) {\n"
- " }\n"
- " BOOST_FOREACH(Item *item, itemlist) {\n"
- " }\n"
- " UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
- "}",
- Style);
-
- // As function-like macros.
- verifyFormat("#define foreach(x, y)\n"
- "#define Q_FOREACH(x, y)\n"
- "#define BOOST_FOREACH(x, y)\n"
- "#define UNKNOWN_FOREACH(x, y)");
-
- // Not as function-like macros.
- verifyFormat("#define foreach (x, y)\n"
- "#define Q_FOREACH (x, y)\n"
- "#define BOOST_FOREACH (x, y)\n"
- "#define UNKNOWN_FOREACH (x, y)");
-
- // handle microsoft non standard extension
- verifyFormat("for each (char c in x->MyStringProperty)");
-}
-
-TEST_F(FormatTest, FormatsWhileLoop) {
- verifyFormat("while (true) {\n}");
- verifyFormat("while (true)\n"
- " f();");
- verifyFormat("while () {\n}");
- verifyFormat("while () {\n"
- " f();\n"
- "}");
-}
-
-TEST_F(FormatTest, FormatsDoWhile) {
- verifyFormat("do {\n"
- " do_something();\n"
- "} while (something());");
- verifyFormat("do\n"
- " do_something();\n"
- "while (something());");
-}
-
-TEST_F(FormatTest, FormatsSwitchStatement) {
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- " f();\n"
- " break;\n"
- "case kFoo:\n"
- "case ns::kBar:\n"
- "case kBaz:\n"
- " break;\n"
- "default:\n"
- " g();\n"
- " break;\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1: {\n"
- " f();\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " break;\n"
- "}\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1: {\n"
- " f();\n"
- " {\n"
- " g();\n"
- " h();\n"
- " }\n"
- " break;\n"
- "}\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1: {\n"
- " f();\n"
- " if (foo) {\n"
- " g();\n"
- " h();\n"
- " }\n"
- " break;\n"
- "}\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1: {\n"
- " f();\n"
- " g();\n"
- "} break;\n"
- "}");
- verifyFormat("switch (test)\n"
- " ;");
- verifyFormat("switch (x) {\n"
- "default: {\n"
- " // Do nothing.\n"
- "}\n"
- "}");
- verifyFormat("switch (x) {\n"
- "// comment\n"
- "// if 1, do f()\n"
- "case 1:\n"
- " f();\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- " // Do amazing stuff\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- " break;\n"
- "}");
- verifyFormat("#define A \\\n"
- " switch (x) { \\\n"
- " case a: \\\n"
- " foo = b; \\\n"
- " }",
- getLLVMStyleWithColumns(20));
- verifyFormat("#define OPERATION_CASE(name) \\\n"
- " case OP_name: \\\n"
- " return operations::Operation##name",
- getLLVMStyleWithColumns(40));
- verifyFormat("switch (x) {\n"
- "case 1:;\n"
- "default:;\n"
- " int i;\n"
- "}");
-
- verifyGoogleFormat("switch (x) {\n"
- " case 1:\n"
- " f();\n"
- " break;\n"
- " case kFoo:\n"
- " case ns::kBar:\n"
- " case kBaz:\n"
- " break;\n"
- " default:\n"
- " g();\n"
- " break;\n"
- "}");
- verifyGoogleFormat("switch (x) {\n"
- " case 1: {\n"
- " f();\n"
- " break;\n"
- " }\n"
- "}");
- verifyGoogleFormat("switch (test)\n"
- " ;");
-
- verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
- " case OP_name: \\\n"
- " return operations::Operation##name");
- verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
- " // Get the correction operation class.\n"
- " switch (OpCode) {\n"
- " CASE(Add);\n"
- " CASE(Subtract);\n"
- " default:\n"
- " return operations::Unknown;\n"
- " }\n"
- "#undef OPERATION_CASE\n"
- "}");
- verifyFormat("DEBUG({\n"
- " switch (x) {\n"
- " case A:\n"
- " f();\n"
- " break;\n"
- " // fallthrough\n"
- " case B:\n"
- " g();\n"
- " break;\n"
- " }\n"
- "});");
- verifyNoChange("DEBUG({\n"
- " switch (x) {\n"
- " case A:\n"
- " f();\n"
- " break;\n"
- " // On B:\n"
- " case B:\n"
- " g();\n"
- " break;\n"
- " }\n"
- "});");
- verifyFormat("switch (n) {\n"
- "case 0: {\n"
- " return false;\n"
- "}\n"
- "default: {\n"
- " return true;\n"
- "}\n"
- "}",
- "switch (n)\n"
- "{\n"
- "case 0: {\n"
- " return false;\n"
- "}\n"
- "default: {\n"
- " return true;\n"
- "}\n"
- "}");
- verifyFormat("switch (a) {\n"
- "case (b):\n"
- " return;\n"
- "}");
-
- verifyFormat("switch (a) {\n"
- "case some_namespace::\n"
- " some_constant:\n"
- " return;\n"
- "}",
- getLLVMStyleWithColumns(34));
-
- verifyFormat("switch (a) {\n"
- "[[likely]] case 1:\n"
- " return;\n"
- "}");
- verifyFormat("switch (a) {\n"
- "[[likely]] [[other::likely]] case 1:\n"
- " return;\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- " return;\n"
- "[[likely]] case 2:\n"
- " return;\n"
- "}");
- verifyFormat("switch (a) {\n"
- "case 1:\n"
- "[[likely]] case 2:\n"
- " return;\n"
- "}");
- FormatStyle Attributes = getLLVMStyle();
- Attributes.AttributeMacros.push_back("LIKELY");
- Attributes.AttributeMacros.push_back("OTHER_LIKELY");
- verifyFormat("switch (a) {\n"
- "LIKELY case b:\n"
- " return;\n"
- "}",
- Attributes);
- verifyFormat("switch (a) {\n"
- "LIKELY OTHER_LIKELY() case b:\n"
- " return;\n"
- "}",
- Attributes);
- verifyFormat("switch (a) {\n"
- "case 1:\n"
- " return;\n"
- "LIKELY case 2:\n"
- " return;\n"
- "}",
- Attributes);
- verifyFormat("switch (a) {\n"
- "case 1:\n"
- "LIKELY case 2:\n"
- " return;\n"
- "}",
- Attributes);
-
- FormatStyle Style = getLLVMStyle();
- Style.IndentCaseLabels = true;
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterCaseLabel = true;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- verifyFormat("switch (n)\n"
- "{\n"
- " case 0:\n"
- " {\n"
- " return false;\n"
- " }\n"
- " default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- "switch (n) {\n"
- " case 0: {\n"
- " return false;\n"
- " }\n"
- " default: {\n"
- " return true;\n"
- " }\n"
- "}",
- Style);
- Style.BraceWrapping.AfterCaseLabel = false;
- verifyFormat("switch (n)\n"
- "{\n"
- " case 0: {\n"
- " return false;\n"
- " }\n"
- " default: {\n"
- " return true;\n"
- " }\n"
- "}",
- "switch (n) {\n"
- " case 0:\n"
- " {\n"
- " return false;\n"
- " }\n"
- " default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- Style);
- Style.IndentCaseLabels = false;
- Style.IndentCaseBlocks = true;
- verifyFormat("switch (n)\n"
- "{\n"
- "case 0:\n"
- " {\n"
- " return false;\n"
- " }\n"
- "case 1:\n"
- " break;\n"
- "default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- "switch (n) {\n"
- "case 0: {\n"
- " return false;\n"
- "}\n"
- "case 1:\n"
- " break;\n"
- "default: {\n"
- " return true;\n"
- "}\n"
- "}",
- Style);
- Style.IndentCaseLabels = true;
- Style.IndentCaseBlocks = true;
- verifyFormat("switch (n)\n"
- "{\n"
- " case 0:\n"
- " {\n"
- " return false;\n"
- " }\n"
- " case 1:\n"
- " break;\n"
- " default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- "switch (n) {\n"
- "case 0: {\n"
- " return false;\n"
- "}\n"
- "case 1:\n"
- " break;\n"
- "default: {\n"
- " return true;\n"
- "}\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, CaseRanges) {
- verifyFormat("switch (x) {\n"
- "case 'A' ... 'Z':\n"
- "case 1 ... 5:\n"
- "case a ... b:\n"
- " break;\n"
- "}");
-}
-
-TEST_F(FormatTest, ShortEnums) {
- FormatStyle Style = getLLVMStyle();
- EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
- EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
- verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
- verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
- Style.AllowShortEnumsOnASingleLine = false;
- verifyFormat("enum {\n"
- " A,\n"
- " B,\n"
- " C\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
- verifyFormat("typedef enum {\n"
- " A,\n"
- " B,\n"
- " C\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
- verifyFormat("enum {\n"
- " A,\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
- verifyFormat("typedef enum {\n"
- " A,\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterEnum = true;
- verifyFormat("enum\n"
- "{\n"
- " A,\n"
- " B,\n"
- " C\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
- verifyFormat("typedef enum\n"
- "{\n"
- " A,\n"
- " B,\n"
- " C\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
-
- Style.AllowShortEnumsOnASingleLine = true;
- verifyFormat("export enum\n"
- "{\n"
- " A,\n"
- " B,\n"
- " C\n"
- "} ShortEnum1, ShortEnum2;",
- Style);
-}
-
-TEST_F(FormatTest, ShortCompoundRequirement) {
- constexpr StringRef Code("template <typename T>\n"
- "concept c = requires(T x) {\n"
- " { x + 1 } -> std::same_as<int>;\n"
- "};");
-
- FormatStyle Style = getLLVMStyle();
- EXPECT_TRUE(Style.AllowShortCompoundRequirementOnASingleLine);
- verifyFormat(Code, Style);
- verifyFormat("template <typename T>\n"
- "concept c = requires(T x) {\n"
- " { x + 1 } -> std::same_as<int>;\n"
- " { x + 2 } -> std::same_as<int>;\n"
- "};",
- Style);
-
- Style.AllowShortCompoundRequirementOnASingleLine = false;
- verifyFormat("template <typename T>\n"
- "concept c = requires(T x) {\n"
- " {\n"
- " x + 1\n"
- " } -> std::same_as<int>;\n"
- "};",
- Code, Style);
- verifyFormat("template <typename T>\n"
- "concept c = requires(T x) {\n"
- " {\n"
- " x + 1\n"
- " } -> std::same_as<int>;\n"
- " {\n"
- " x + 2\n"
- " } -> std::same_as<int>;\n"
- "};",
- Style);
-
- Style.AllowShortCompoundRequirementOnASingleLine = true;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
- verifyFormat(Code, Style);
-}
-
-TEST_F(FormatTest, ShortCaseLabels) {
- FormatStyle Style = getLLVMStyle();
- Style.AllowShortCaseLabelsOnASingleLine = true;
- verifyFormat("switch (a) {\n"
- "case 1: x = 1; break;\n"
- "case 2: return;\n"
- "case 3:\n"
- "case 4:\n"
- "case 5: return;\n"
- "case 6: // comment\n"
- " return;\n"
- "case 7:\n"
- " // comment\n"
- " return;\n"
- "case 8:\n"
- " x = 8; // comment\n"
- " break;\n"
- "default: y = 1; break;\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "case 0: return; // comment\n"
- "case 1: break; // comment\n"
- "case 2: return;\n"
- "// comment\n"
- "case 3: return;\n"
- "// comment 1\n"
- "// comment 2\n"
- "// comment 3\n"
- "case 4: break; /* comment */\n"
- "case 5:\n"
- " // comment\n"
- " break;\n"
- "case 6: /* comment */ x = 1; break;\n"
- "case 7: x = /* comment */ 1; break;\n"
- "case 8:\n"
- " x = 1; /* comment */\n"
- " break;\n"
- "case 9:\n"
- " break; // comment line 1\n"
- " // comment line 2\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "case 1:\n"
- " x = 8;\n"
- " // fall through\n"
- "case 2: x = 8;\n"
- "// comment\n"
- "case 3:\n"
- " return; /* comment line 1\n"
- " * comment line 2 */\n"
- "case 4: i = 8;\n"
- "// something else\n"
- "#if FOO\n"
- "case 5: break;\n"
- "#endif\n"
- "}",
- "switch (a) {\n"
- "case 1: x = 8;\n"
- " // fall through\n"
- "case 2:\n"
- " x = 8;\n"
- "// comment\n"
- "case 3:\n"
- " return; /* comment line 1\n"
- " * comment line 2 */\n"
- "case 4:\n"
- " i = 8;\n"
- "// something else\n"
- "#if FOO\n"
- "case 5: break;\n"
- "#endif\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "case 0:\n"
- " return; // long long long long long long long long long long "
- "long long comment\n"
- " // line\n"
- "}",
- "switch (a) {\n"
- "case 0: return; // long long long long long long long long "
- "long long long long comment line\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "case 0:\n"
- " return; /* long long long long long long long long long long "
- "long long comment\n"
- " line */\n"
- "}",
- "switch (a) {\n"
- "case 0: return; /* long long long long long long long long "
- "long long long long comment line */\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "#if FOO\n"
- "case 0: return 0;\n"
- "#endif\n"
- "}",
- Style);
- verifyFormat("switch (a) {\n"
- "case 1: {\n"
- "}\n"
- "case 2: {\n"
- " return;\n"
- "}\n"
- "case 3: {\n"
- " x = 1;\n"
- " return;\n"
- "}\n"
- "case 4:\n"
- " if (x)\n"
- " return;\n"
- "}",
- Style);
- Style.ColumnLimit = 21;
- verifyFormat("#define X \\\n"
- " case 0: break;\n"
- "#include \"f\"",
- Style);
- verifyFormat("switch (a) {\n"
- "case 1: x = 1; break;\n"
- "case 2: return;\n"
- "case 3:\n"
- "case 4:\n"
- "case 5: return;\n"
- "default:\n"
- " y = 1;\n"
- " break;\n"
- "}",
- Style);
- Style.ColumnLimit = 80;
- Style.AllowShortCaseLabelsOnASingleLine = false;
- Style.IndentCaseLabels = true;
- verifyFormat("switch (n) {\n"
- " default /*comments*/:\n"
- " return true;\n"
- " case 0:\n"
- " return false;\n"
- "}",
- "switch (n) {\n"
- "default/*comments*/:\n"
- " return true;\n"
- "case 0:\n"
- " return false;\n"
- "}",
- Style);
- Style.AllowShortCaseLabelsOnASingleLine = true;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterCaseLabel = true;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- verifyFormat("switch (n)\n"
- "{\n"
- " case 0:\n"
- " {\n"
- " return false;\n"
- " }\n"
- " default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- "switch (n) {\n"
- " case 0: {\n"
- " return false;\n"
- " }\n"
- " default:\n"
- " {\n"
- " return true;\n"
- " }\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, FormatsLabels) {
- verifyFormat("void f() {\n"
- " some_code();\n"
- "test_label:\n"
- " some_other_code();\n"
- " {\n"
- " some_more_code();\n"
- " another_label:\n"
- " some_more_code();\n"
- " }\n"
- "}");
- verifyFormat("{\n"
- " some_code();\n"
- "test_label:\n"
- " some_other_code();\n"
- "}");
- verifyFormat("{\n"
- " some_code();\n"
- "test_label:;\n"
- " int i = 0;\n"
- "}");
- verifyFormat("{\n"
- " some_code();\n"
- "test_label: { some_other_code(); }\n"
- "}");
- verifyFormat("{\n"
- " some_code();\n"
- "test_label: {\n"
- " some_other_code();\n"
- " some_other_code();\n"
- "}\n"
- "}");
- verifyFormat("{\n"
- "L0:\n"
- "[[foo]] L1:\n"
- "[[bar]] [[baz]] L2:\n"
- " g();\n"
- "}");
- verifyFormat("{\n"
- "[[foo]] L1: {\n"
- "[[bar]] [[baz]] L2:\n"
- " g();\n"
- "}\n"
- "}");
- verifyFormat("{\n"
- "[[foo]] L1:\n"
- " f();\n"
- " {\n"
- " [[bar]] [[baz]] L2:\n"
- " g();\n"
- " }\n"
- "}");
-
- FormatStyle Style = getLLVMStyle();
- Style.IndentGotoLabels = FormatStyle::IGLS_NoIndent;
- verifyFormat("void f() {\n"
- " some_code();\n"
- "test_label:\n"
- " some_other_code();\n"
- " {\n"
- " some_more_code();\n"
- "another_label:\n"
- " some_more_code();\n"
- " }\n"
- "}",
- Style);
- verifyFormat("{\n"
- " some_code();\n"
- "test_label:\n"
- " some_other_code();\n"
- "}",
- Style);
- verifyFormat("{\n"
- " some_code();\n"
- "test_label:;\n"
- " int i = 0;\n"
- "}",
- Style);
- verifyFormat("{\n"
- " some_code();\n"
- "test_label: { some_other_code(); }\n"
- "}",
- Style);
- verifyFormat("{\n"
- "[[foo]] L1:\n"
- " f();\n"
- " {\n"
- "[[bar]] [[baz]] L2:\n"
- " g();\n"
- " }\n"
- "}",
- Style);
- verifyFormat("void f() {\n"
- "L1:\n"
- " a();\n"
- " {\n"
- "L2:\n"
- " b();\n"
- " {\n"
- "L3:\n"
- " c();\n"
- " {\n"
- "L4:\n"
- " }\n"
- " }\n"
- " }\n"
- "}",
- Style);
- Style.IndentGotoLabels = FormatStyle::IGLS_OuterIndent;
- verifyFormat("void f() {\n"
- " some_code();\n"
- "test_label:\n"
- " some_other_code();\n"
- " {\n"
- " some_more_code();\n"
- " another_label:\n"
- " some_more_code();\n"
- " }\n"
- "}",
- Style);
- verifyFormat("void f() {\n"
- "L1:\n"
- " a();\n"
- " {\n"
- " L2:\n"
- " b();\n"
- " {\n"
- " L3:\n"
- " c();\n"
- " {\n"
- " L4:\n"
- " }\n"
- " }\n"
- " }\n"
- "}",
- Style);
- Style.IndentGotoLabels = FormatStyle::IGLS_InnerIndent;
- verifyFormat("void f() {\n"
- " some_code();\n"
- " test_label:\n"
- " some_other_code();\n"
- " {\n"
- " some_more_code();\n"
- " another_label:\n"
- " some_more_code();\n"
- " }\n"
- "}",
- Style);
- verifyFormat("void f() {\n"
- " L1:\n"
- " a();\n"
- " {\n"
- " L2:\n"
- " b();\n"
- " {\n"
- " L3:\n"
- " c();\n"
- " {\n"
- " L4:\n"
- " }\n"
- " }\n"
- " }\n"
- "}",
- Style);
- Style.IndentGotoLabels = FormatStyle::IGLS_HalfIndent;
- verifyFormat("void f() {\n"
- " some_code();\n"
- " test_label:\n"
- " some_other_code();\n"
- " {\n"
- " some_more_code();\n"
- " another_label:\n"
- " some_more_code();\n"
- " }\n"
- "}",
- Style);
- verifyFormat("void f() {\n"
- " L1:\n"
- " a();\n"
- " {\n"
- " L2:\n"
- " b();\n"
- " {\n"
- " L3:\n"
- " c();\n"
- " {\n"
- " L4:\n"
- " }\n"
- " }\n"
- " }\n"
- "}",
- Style);
- Style.IndentWidth = 3;
- verifyFormat("void f() {\n"
- " some_code();\n"
- " test_label:\n"
- " some_other_code();\n"
- "}",
- Style);
- Style.IndentWidth = 2;
- Style.IndentGotoLabels = FormatStyle::IGLS_NoIndent;
-
- Style.ColumnLimit = 15;
- verifyFormat("#define FOO \\\n"
- "label: \\\n"
- " break;",
- Style);
-
- // The opening brace may either be on the same unwrapped line as the colon or
- // on a separate one. The formatter should recognize both.
- Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("{\n"
- " some_code();\n"
- "test_label:\n"
- "{\n"
- " some_other_code();\n"
- "}\n"
- "}",
- Style);
- verifyFormat("{\n"
- "[[foo]] L1:\n"
- "{\n"
- "[[bar]] [[baz]] L2:\n"
- " g();\n"
- "}\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, MultiLineControlStatements) {
- FormatStyle Style = getLLVMStyleWithColumns(20);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
- // Short lines should keep opening brace on same line.
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "}",
- "if(foo){bar();}", Style);
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "} else {\n"
- " baz();\n"
- "}",
- "if(foo){bar();}else{baz();}", Style);
- verifyFormat("if (foo && bar) {\n"
- " baz();\n"
- "}",
- "if(foo&&bar){baz();}", Style);
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "} else if (baz) {\n"
- " quux();\n"
- "}",
- "if(foo){bar();}else if(baz){quux();}", Style);
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "} else if (baz) {\n"
- " quux();\n"
- "} else {\n"
- " foobar();\n"
- "}",
- "if(foo){bar();}else if(baz){quux();}else{foobar();}", Style);
- verifyFormat("for (;;) {\n"
- " foo();\n"
- "}",
- "for(;;){foo();}");
- verifyFormat("while (1) {\n"
- " foo();\n"
- "}",
- "while(1){foo();}", Style);
- verifyFormat("switch (foo) {\n"
- "case bar:\n"
- " return;\n"
- "}",
- "switch(foo){case bar:return;}", Style);
- verifyFormat("try {\n"
- " foo();\n"
- "} catch (...) {\n"
- " bar();\n"
- "}",
- "try{foo();}catch(...){bar();}", Style);
- verifyFormat("do {\n"
- " foo();\n"
- "} while (bar &&\n"
- " baz);",
- "do{foo();}while(bar&&baz);", Style);
- // Long lines should put opening brace on new line.
- verifyFormat("void f() {\n"
- " if (a1 && a2 &&\n"
- " a3)\n"
- " {\n"
- " quux();\n"
- " }\n"
- "}",
- "void f(){if(a1&&a2&&a3){quux();}}", Style);
- verifyFormat("if (foo && bar &&\n"
- " baz)\n"
- "{\n"
- " quux();\n"
- "}",
- "if(foo&&bar&&baz){quux();}", Style);
- verifyFormat("if (foo && bar &&\n"
- " baz)\n"
- "{\n"
- " quux();\n"
- "}",
- "if (foo && bar &&\n"
- " baz) {\n"
- " quux();\n"
- "}",
- Style);
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "} else if (baz ||\n"
- " quux)\n"
- "{\n"
- " foobar();\n"
- "}",
- "if(foo){bar();}else if(baz||quux){foobar();}", Style);
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "} else if (baz ||\n"
- " quux)\n"
- "{\n"
- " foobar();\n"
- "} else {\n"
- " barbaz();\n"
- "}",
- "if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
- Style);
- verifyFormat("for (int i = 0;\n"
- " i < 10; ++i)\n"
- "{\n"
- " foo();\n"
- "}",
- "for(int i=0;i<10;++i){foo();}", Style);
- verifyFormat("foreach (int i,\n"
- " list)\n"
- "{\n"
- " foo();\n"
- "}",
- "foreach(int i, list){foo();}", Style);
- Style.ColumnLimit =
- 40; // to concentrate at brace wrapping, not line wrap due to column limit
- verifyFormat("foreach (int i, list) {\n"
- " foo();\n"
- "}",
- "foreach(int i, list){foo();}", Style);
- Style.ColumnLimit =
- 20; // to concentrate at brace wrapping, not line wrap due to column limit
- verifyFormat("while (foo || bar ||\n"
- " baz)\n"
- "{\n"
- " quux();\n"
- "}",
- "while(foo||bar||baz){quux();}", Style);
- verifyFormat("switch (\n"
- " foo = barbaz)\n"
- "{\n"
- "case quux:\n"
- " return;\n"
- "}",
- "switch(foo=barbaz){case quux:return;}", Style);
- verifyFormat("try {\n"
- " foo();\n"
- "} catch (\n"
- " Exception &bar)\n"
- "{\n"
- " baz();\n"
- "}",
- "try{foo();}catch(Exception&bar){baz();}", Style);
- Style.ColumnLimit =
- 40; // to concentrate at brace wrapping, not line wrap due to column limit
- verifyFormat("try {\n"
- " foo();\n"
- "} catch (Exception &bar) {\n"
- " baz();\n"
- "}",
- "try{foo();}catch(Exception&bar){baz();}", Style);
- Style.ColumnLimit =
- 20; // to concentrate at brace wrapping, not line wrap due to column limit
-
- Style.BraceWrapping.BeforeElse = true;
- verifyFormat("if (foo) {\n"
- " bar();\n"
- "}\n"
- "else if (baz ||\n"
- " quux)\n"
- "{\n"
- " foobar();\n"
- "}\n"
- "else {\n"
- " barbaz();\n"
- "}",
- "if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
- Style);
-
- Style.BraceWrapping.BeforeCatch = true;
- verifyFormat("try {\n"
- " foo();\n"
- "}\n"
- "catch (...) {\n"
- " baz();\n"
- "}",
- "try{foo();}catch(...){baz();}", Style);
-
- Style.BraceWrapping.AfterFunction = true;
- Style.BraceWrapping.AfterStruct = false;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- Style.ColumnLimit = 80;
- verifyFormat("void shortfunction() { bar(); }", Style);
- verifyFormat("struct T shortfunction() { return bar(); }", Style);
- verifyFormat("struct T {};", Style);
-
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- verifyFormat("void shortfunction()\n"
- "{\n"
- " bar();\n"
- "}",
- Style);
- verifyFormat("struct T shortfunction()\n"
- "{\n"
- " return bar();\n"
- "}",
- Style);
- verifyFormat("struct T {};", Style);
-
- Style.BraceWrapping.AfterFunction = false;
- Style.BraceWrapping.AfterStruct = true;
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- verifyFormat("void shortfunction() { bar(); }", Style);
- verifyFormat("struct T shortfunction() { return bar(); }", Style);
- verifyFormat("struct T\n"
- "{\n"
- "};",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- verifyFormat("void shortfunction() {\n"
- " bar();\n"
- "}",
- Style);
- verifyFormat("struct T shortfunction() {\n"
- " return bar();\n"
- "}",
- Style);
- verifyFormat("struct T\n"
- "{\n"
- "};",
- Style);
-
- Style = getLLVMStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
- Style.AllowShortLoopsOnASingleLine = true;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
- verifyFormat("if (true) { return; }", Style);
- verifyFormat("while (true) { return; }", Style);
- // Failing test in https://reviews.llvm.org/D114521#3151727
- verifyFormat("for (;;) { bar(); }", Style);
-}
-
-TEST_F(FormatTest, BeforeWhile) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
-
- verifyFormat("do {\n"
- " foo();\n"
- "} while (1);",
- Style);
- Style.BraceWrapping.BeforeWhile = true;
- verifyFormat("do {\n"
- " foo();\n"
- "}\n"
- "while (1);",
- Style);
-}
-
-//===----------------------------------------------------------------------===//
-// Tests for classes, namespaces, etc.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
- verifyFormat("class A {};");
-}
-
-TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
- verifyFormat("class A {\n"
- "public:\n"
- "public: // comment\n"
- "protected:\n"
- "private:\n"
- " void f() {}\n"
- "};");
- verifyFormat("export class A {\n"
- "public:\n"
- "public: // comment\n"
- "protected:\n"
- "private:\n"
- " void f() {}\n"
- "};");
- verifyGoogleFormat("class A {\n"
- " public:\n"
- " protected:\n"
- " private:\n"
- " void f() {}\n"
- "};");
- verifyGoogleFormat("export class A {\n"
- " public:\n"
- " protected:\n"
- " private:\n"
- " void f() {}\n"
- "};");
- verifyFormat("class A {\n"
- "public slots:\n"
- " void f1() {}\n"
- "public Q_SLOTS:\n"
- " void f2() {}\n"
- "protected slots:\n"
- " void f3() {}\n"
- "protected Q_SLOTS:\n"
- " void f4() {}\n"
- "private slots:\n"
- " void f5() {}\n"
- "private Q_SLOTS:\n"
- " void f6() {}\n"
- "signals:\n"
- " void g1();\n"
- "Q_SIGNALS:\n"
- " void g2();\n"
- "};");
-
- // Don't interpret 'signals' the wrong way.
- verifyFormat("signals.set();");
- verifyFormat("for (Signals signals : f()) {\n}");
- verifyFormat("{\n"
- " signals.set(); // This needs indentation.\n"
- "}");
- verifyFormat("void f() {\n"
- "label:\n"
- " signals.baz();\n"
- "}");
-
- const auto Style = getLLVMStyle(FormatStyle::LK_C);
- verifyFormat("private[1];", Style);
- verifyFormat("testArray[public] = 1;");
- verifyFormat("public();", Style);
- verifyFormat("myFunc(public);");
- verifyFormat("std::vector<int> testVec = {private};");
- verifyFormat("private.p = 1;", Style);
- verifyFormat("void function(private...) {};");
- verifyFormat("if (private && public)");
- verifyFormat("private &= true;", Style);
- verifyFormat("int x = private * public;");
- verifyFormat("public *= private;", Style);
- verifyFormat("int x = public + private;");
- verifyFormat("private++;", Style);
- verifyFormat("++private;");
- verifyFormat("public += private;", Style);
- verifyFormat("public = public - private;", Style);
- verifyFormat("public->foo();", Style);
- verifyFormat("private--;", Style);
- verifyFormat("--private;");
- verifyFormat("public -= 1;", Style);
- verifyFormat("if (!private && !public)");
- verifyFormat("public != private;", Style);
- verifyFormat("int x = public / private;");
- verifyFormat("public /= 2;", Style);
- verifyFormat("public = public % 2;", Style);
- verifyFormat("public %= 2;", Style);
- verifyFormat("if (public < private)");
- verifyFormat("public << private;", Style);
- verifyFormat("public <<= private;", Style);
- verifyFormat("if (public > private)");
- verifyFormat("public >> private;", Style);
- verifyFormat("public >>= private;", Style);
- verifyFormat("public ^ private;", Style);
- verifyFormat("public ^= private;", Style);
- verifyFormat("public | private;", Style);
- verifyFormat("public |= private;", Style);
- verifyFormat("auto x = private ? 1 : 2;");
- verifyFormat("if (public == private)");
- verifyFormat("void foo(public, private)");
-
- verifyFormat("class A {\n"
- "public:\n"
- " std::unique_ptr<int *[]> b() { return nullptr; }\n"
- "\n"
- "private:\n"
- " int c;\n"
- "};\n"
- "class B {\n"
- "public:\n"
- " std::unique_ptr<int *[] /* okay */> b() { return nullptr; }\n"
- "\n"
- "private:\n"
- " int c;\n"
- "};");
-}
-
-TEST_F(FormatTest, SeparatesLogicalBlocks) {
- verifyFormat("class A {\n"
- "public:\n"
- " void f();\n"
- "\n"
- "private:\n"
- " void g() {}\n"
- " // test\n"
- "protected:\n"
- " int h;\n"
- "};",
- "class A {\n"
- "public:\n"
- "void f();\n"
- "private:\n"
- "void g() {}\n"
- "// test\n"
- "protected:\n"
- "int h;\n"
- "};");
- verifyFormat("class A {\n"
- "protected:\n"
- "public:\n"
- " void f();\n"
- "};",
- "class A {\n"
- "protected:\n"
- "\n"
- "public:\n"
- "\n"
- " void f();\n"
- "};");
-
- // Even ensure proper spacing inside macros.
- verifyFormat("#define B \\\n"
- " class A { \\\n"
- " protected: \\\n"
- " public: \\\n"
- " void f(); \\\n"
- " };",
- "#define B \\\n"
- " class A { \\\n"
- " protected: \\\n"
- " \\\n"
- " public: \\\n"
- " \\\n"
- " void f(); \\\n"
- " };",
- getGoogleStyle());
- // But don't remove empty lines after macros ending in access specifiers.
- verifyFormat("#define A private:\n"
- "\n"
- "int i;",
- "#define A private:\n"
- "\n"
- "int i;");
-}
-
-TEST_F(FormatTest, FormatsClasses) {
- verifyFormat("class A : public B {};");
- verifyFormat("class A : public ::B {};");
-
- verifyFormat(
- "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
- " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
- verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
- " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
- " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
- verifyFormat(
- "class A : public B, public C, public D, public E, public F {};");
- verifyFormat("class AAAAAAAAAAAA : public B,\n"
- " public C,\n"
- " public D,\n"
- " public E,\n"
- " public F,\n"
- " public G {};");
-
- verifyFormat("class\n"
- " ReallyReallyLongClassName {\n"
- " int i;\n"
- "};",
- getLLVMStyleWithColumns(32));
- verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
- " aaaaaaaaaaaaaaaa> {};");
- verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
- " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaa> {};");
- verifyFormat("template <class R, class C>\n"
- "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
- " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
- verifyFormat("class ::A::B {};");
-}
-
-TEST_F(FormatTest, BreakInheritanceStyle) {
- FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
- StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
- FormatStyle::BILS_BeforeComma;
- verifyFormat("class MyClass : public X {};",
- StyleWithInheritanceBreakBeforeComma);
- verifyFormat("class MyClass\n"
- " : public X\n"
- " , public Y {};",
- StyleWithInheritanceBreakBeforeComma);
- verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
- " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
- " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
- StyleWithInheritanceBreakBeforeComma);
- verifyFormat("struct aaaaaaaaaaaaa\n"
- " : public aaaaaaaaaaaaaaaaaaa< // break\n"
- " aaaaaaaaaaaaaaaa> {};",
- StyleWithInheritanceBreakBeforeComma);
-
- FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
- StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
- FormatStyle::BILS_AfterColon;
- verifyFormat("class MyClass : public X {};",
- StyleWithInheritanceBreakAfterColon);
- verifyFormat("class MyClass : public X, public Y {};",
- StyleWithInheritanceBreakAfterColon);
- verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
- " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
- " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
- StyleWithInheritanceBreakAfterColon);
- verifyFormat("struct aaaaaaaaaaaaa :\n"
- " public aaaaaaaaaaaaaaaaaaa< // break\n"
- " aaaaaaaaaaaaaaaa> {};",
- StyleWithInheritanceBreakAfterColon);
-
- FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
- StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
- FormatStyle::BILS_AfterComma;
- verifyFormat("class MyClass : public X {};",
- StyleWithInheritanceBreakAfterComma);
- verifyFormat("class MyClass : public X,\n"
- " public Y {};",
- StyleWithInheritanceBreakAfterComma);
- verifyFormat(
- "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
- " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
- "{};",
- StyleWithInheritanceBreakAfterComma);
- verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
- " aaaaaaaaaaaaaaaa> {};",
- StyleWithInheritanceBreakAfterComma);
- verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
- " : public OnceBreak,\n"
- " public AlwaysBreak,\n"
- " EvenBasesFitInOneLine {};",
- StyleWithInheritanceBreakAfterComma);
-}
-
-TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
- verifyFormat("class A {\n} a, b;");
- verifyFormat("struct A {\n} a, b;");
- verifyFormat("union A {\n} a, b;");
-
- verifyFormat("constexpr class A {\n} a, b;");
- verifyFormat("constexpr struct A {\n} a, b;");
- verifyFormat("constexpr union A {\n} a, b;");
-
- verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
- verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
- verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
-
- verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
- verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
- verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
-
- verifyFormat("namespace ns {\n"
- "class {\n"
- "} a, b;\n"
- "} // namespace ns");
- verifyFormat("namespace ns {\n"
- "const class {\n"
- "} a, b;\n"
- "} // namespace ns");
- verifyFormat("namespace ns {\n"
- "constexpr class C {\n"
- "} a, b;\n"
- "} // namespace ns");
- verifyFormat("namespace ns {\n"
- "class { /* comment */\n"
- "} a, b;\n"
- "} // namespace ns");
- verifyFormat("namespace ns {\n"
- "const class { /* comment */\n"
- "} a, b;\n"
- "} // namespace ns");
-}
-
-TEST_F(FormatTest, FormatsEnum) {
- verifyFormat("enum {\n"
- " Zero,\n"
- " One = 1,\n"
- " Two = One + 1,\n"
- " Three = (One + Two),\n"
- " Four = (Zero && (One ^ Two)) | (One << Two),\n"
- " Five = (One, Two, Three, Four, 5)\n"
- "};");
- verifyGoogleFormat("enum {\n"
- " Zero,\n"
- " One = 1,\n"
- " Two = One + 1,\n"
- " Three = (One + Two),\n"
- " Four = (Zero && (One ^ Two)) | (One << Two),\n"
- " Five = (One, Two, Three, Four, 5)\n"
- "};");
- verifyFormat("enum Enum {};");
- verifyFormat("enum {};");
- verifyFormat("enum X E {} d;");
- verifyFormat("enum __attribute__((...)) E {} d;");
- verifyFormat("enum __declspec__((...)) E {} d;");
- verifyFormat("enum [[nodiscard]] E {} d;");
- verifyFormat("enum {\n"
- " Bar = Foo<int, int>::value\n"
- "};",
- getLLVMStyleWithColumns(30));
-
- verifyFormat("enum ShortEnum { A, B, C };");
- verifyGoogleFormat("enum ShortEnum { A, B, C };");
-
- verifyFormat("enum KeepEmptyLines {\n"
- " ONE,\n"
- "\n"
- " TWO,\n"
- "\n"
- " THREE\n"
- "}",
- "enum KeepEmptyLines {\n"
- " ONE,\n"
- "\n"
- " TWO,\n"
- "\n"
- "\n"
- " THREE\n"
- "}");
- verifyFormat("enum E { // comment\n"
- " ONE,\n"
- " TWO\n"
- "};\n"
- "int i;");
-
- FormatStyle EightIndent = getLLVMStyle();
- EightIndent.IndentWidth = 8;
- verifyFormat("enum {\n"
- " VOID,\n"
- " CHAR,\n"
- " SHORT,\n"
- " INT,\n"
- " LONG,\n"
- " SIGNED,\n"
- " UNSIGNED,\n"
- " BOOL,\n"
- " FLOAT,\n"
- " DOUBLE,\n"
- " COMPLEX\n"
- "};",
- EightIndent);
-
- verifyFormat("enum [[nodiscard]] E {\n"
- " ONE,\n"
- " TWO,\n"
- "};");
- verifyFormat("enum [[nodiscard]] E {\n"
- " // Comment 1\n"
- " ONE,\n"
- " // Comment 2\n"
- " TWO,\n"
- "};");
- verifyFormat("enum [[clang::enum_extensibility(open)]] E {\n"
- " // Comment 1\n"
- " ONE,\n"
- " // Comment 2\n"
- " TWO\n"
- "};");
- verifyFormat("enum [[nodiscard]] [[clang::enum_extensibility(open)]] E {\n"
- " // Comment 1\n"
- " ONE,\n"
- " // Comment 2\n"
- " TWO\n"
- "};");
- verifyFormat("enum [[clang::enum_extensibility(open)]] E { // foo\n"
- " A,\n"
- " // bar\n"
- " B\n"
- "};",
- "enum [[clang::enum_extensibility(open)]] E{// foo\n"
- " A,\n"
- " // bar\n"
- " B};");
-
- // Not enums.
- verifyFormat("enum X f() {\n"
- " a();\n"
- " return 42;\n"
- "}");
- verifyFormat("enum X Type::f() {\n"
- " a();\n"
- " return 42;\n"
- "}");
- verifyFormat("enum ::X f() {\n"
- " a();\n"
- " return 42;\n"
- "}");
- verifyFormat("enum ns::X f() {\n"
- " a();\n"
- " return 42;\n"
- "}");
-}
-
-TEST_F(FormatTest, FormatsEnumsWithErrors) {
- verifyFormat("enum Type {\n"
- " One = 0; // These semicolons should be commas.\n"
- " Two = 1;\n"
- "};");
- verifyFormat("namespace n {\n"
- "enum Type {\n"
- " One,\n"
- " Two, // missing };\n"
- " int i;\n"
- "}\n"
- "void g() {}");
-}
-
-TEST_F(FormatTest, FormatsEnumStruct) {
- verifyFormat("enum struct {\n"
- " Zero,\n"
- " One = 1,\n"
- " Two = One + 1,\n"
- " Three = (One + Two),\n"
- " Four = (Zero && (One ^ Two)) | (One << Two),\n"
- " Five = (One, Two, Three, Four, 5)\n"
- "};");
- verifyFormat("enum struct Enum {};");
- verifyFormat("enum struct {};");
- verifyFormat("enum struct X E {} d;");
- verifyFormat("enum struct __attribute__((...)) E {} d;");
- verifyFormat("enum struct __declspec__((...)) E {} d;");
- verifyFormat("enum struct [[nodiscard]] E {} d;");
- verifyFormat("enum struct X f() {\n a();\n return 42;\n}");
-
- verifyFormat("enum struct [[nodiscard]] E {\n"
- " ONE,\n"
- " TWO,\n"
- "};");
- verifyFormat("enum struct [[nodiscard]] E {\n"
- " // Comment 1\n"
- " ONE,\n"
- " // Comment 2\n"
- " TWO,\n"
- "};");
-}
-
-TEST_F(FormatTest, FormatsEnumClass) {
- verifyFormat("enum class {\n"
- " Zero,\n"
- " One = 1,\n"
- " Two = One + 1,\n"
- " Three = (One + Two),\n"
- " Four = (Zero && (One ^ Two)) | (One << Two),\n"
- " Five = (One, Two, Three, Four, 5)\n"
- "};");
- verifyFormat("enum class Enum {};");
- verifyFormat("enum class {};");
- verifyFormat("enum class X E {} d;");
- verifyFormat("enum class __attribute__((...)) E {} d;");
- verifyFormat("enum class __declspec__((...)) E {} d;");
- verifyFormat("enum class [[nodiscard]] E {} d;");
- verifyFormat("enum class X f() {\n a();\n return 42;\n}");
-
- verifyFormat("enum class [[nodiscard]] E {\n"
- " ONE,\n"
- " TWO,\n"
- "};");
- verifyFormat("enum class [[nodiscard]] E {\n"
- " // Comment 1\n"
- " ONE,\n"
- " // Comment 2\n"
- " TWO,\n"
- "};");
-}
-
-TEST_F(FormatTest, FormatsEnumTypes) {
- verifyFormat("enum X : int {\n"
- " A, // Force multiple lines.\n"
- " B\n"
- "};");
- verifyFormat("enum X : int { A, B };");
- verifyFormat("enum X : std::uint32_t { A, B };");
-}
-
-TEST_F(FormatTest, FormatsTypedefEnum) {
- FormatStyle Style = getLLVMStyleWithColumns(40);
- verifyFormat("typedef enum {} EmptyEnum;");
- verifyFormat("typedef enum { A, B, C } ShortEnum;");
- verifyFormat("typedef enum {\n"
- " ZERO = 0,\n"
- " ONE = 1,\n"
- " TWO = 2,\n"
- " THREE = 3\n"
- "} LongEnum;",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterEnum = true;
- verifyFormat("typedef enum {} EmptyEnum;");
- verifyFormat("typedef enum { A, B, C } ShortEnum;");
- verifyFormat("typedef enum\n"
- "{\n"
- " ZERO = 0,\n"
- " ONE = 1,\n"
- " TWO = 2,\n"
- " THREE = 3\n"
- "} LongEnum;",
- Style);
-}
-
-TEST_F(FormatTest, FormatsNSEnums) {
- verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
- verifyGoogleFormat(
- "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
- verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
- " // Information about someDecentlyLongValue.\n"
- " someDecentlyLongValue,\n"
- " // Information about anotherDecentlyLongValue.\n"
- " anotherDecentlyLongValue,\n"
- " // Information about aThirdDecentlyLongValue.\n"
- " aThirdDecentlyLongValue\n"
- "};");
- verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
- " // Information about someDecentlyLongValue.\n"
- " someDecentlyLongValue,\n"
- " // Information about anotherDecentlyLongValue.\n"
- " anotherDecentlyLongValue,\n"
- " // Information about aThirdDecentlyLongValue.\n"
- " aThirdDecentlyLongValue\n"
- "};");
- verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
- " a = 1,\n"
- " b = 2,\n"
- " c = 3,\n"
- "};");
- verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
- " a = 1,\n"
- " b = 2,\n"
- " c = 3,\n"
- "};");
- verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
- " a = 1,\n"
- " b = 2,\n"
- " c = 3,\n"
- "};");
- verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
- " a = 1,\n"
- " b = 2,\n"
- " c = 3,\n"
- "};");
-}
-
-TEST_F(FormatTest, FormatsBitfields) {
- verifyFormat("struct Bitfields {\n"
- " unsigned sClass : 8;\n"
- " unsigned ValueKind : 2;\n"
- "};");
- verifyFormat("struct A {\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
- "};");
- verifyFormat("struct MyStruct {\n"
- " uchar data;\n"
- " uchar : 8;\n"
- " uchar : 8;\n"
- " uchar other;\n"
- "};");
- verifyFormat("struct foo {\n"
- " uint8_t i_am_a_bit_field_this_long\n"
- " : struct_with_constexpr::i_am_a_constexpr_lengthhhhh;\n"
- "};");
- FormatStyle Style = getLLVMStyle();
- Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
- verifyFormat("struct Bitfields {\n"
- " unsigned sClass:8;\n"
- " unsigned ValueKind:2;\n"
- " uchar other;\n"
- "};",
- Style);
- verifyFormat("struct A {\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
- "};",
- Style);
- Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
- verifyFormat("struct Bitfields {\n"
- " unsigned sClass :8;\n"
- " unsigned ValueKind :2;\n"
- " uchar other;\n"
- "};",
- Style);
- Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
- verifyFormat("struct Bitfields {\n"
- " unsigned sClass: 8;\n"
- " unsigned ValueKind: 2;\n"
- " uchar other;\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, FormatsNamespaces) {
- FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
- LLVMWithNoNamespaceFix.FixNamespaceComments = false;
-
- verifyFormat("namespace some_namespace {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("#define M(x) x##x\n"
- "namespace M(x) {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("#define M(x) x##x\n"
- "namespace N::inline M(x) {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("#define M(x) x##x\n"
- "namespace M(x)::inline N {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("#define M(x) x##x\n"
- "namespace N::M(x) {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("#define M(x) x##x\n"
- "namespace M::N(x) {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace N::inline D {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace N::inline D::E {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("/* something */ namespace some_namespace {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("namespace {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("/* something */ namespace {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("inline namespace X {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("/* something */ inline namespace X {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("export namespace X {\n"
- "class A {};\n"
- "void f() { f(); }\n"
- "}",
- LLVMWithNoNamespaceFix);
- verifyFormat("using namespace some_namespace;\n"
- "class A {};\n"
- "void f() { f(); }",
- LLVMWithNoNamespaceFix);
-
- // This code is more common than we thought; if we
- // layout this correctly the semicolon will go into
- // its own line, which is undesirable.
- verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
- verifyFormat("namespace {\n"
- "class A {};\n"
- "};",
- LLVMWithNoNamespaceFix);
-
- verifyFormat("namespace {\n"
- "int SomeVariable = 0; // comment\n"
- "} // namespace",
- LLVMWithNoNamespaceFix);
- verifyFormat("#ifndef HEADER_GUARD\n"
- "#define HEADER_GUARD\n"
- "namespace my_namespace {\n"
- "int i;\n"
- "} // my_namespace\n"
- "#endif // HEADER_GUARD",
- "#ifndef HEADER_GUARD\n"
- " #define HEADER_GUARD\n"
- " namespace my_namespace {\n"
- "int i;\n"
- "} // my_namespace\n"
- "#endif // HEADER_GUARD",
- LLVMWithNoNamespaceFix);
-
- verifyFormat("namespace A::B {\n"
- "class C {};\n"
- "}",
- LLVMWithNoNamespaceFix);
-
- FormatStyle Style = getLLVMStyle();
- Style.NamespaceIndentation = FormatStyle::NI_All;
- verifyFormat("namespace out {\n"
- " int i;\n"
- " namespace in {\n"
- " int i;\n"
- " } // namespace in\n"
- "} // namespace out",
- "namespace out {\n"
- "int i;\n"
- "namespace in {\n"
- "int i;\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
-
- FormatStyle ShortInlineFunctions = getLLVMStyle();
- ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
- ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
- verifyFormat("namespace {\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace { /* comment */\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace { // comment\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " int some_int;\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace interface {\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace interface",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " class X {\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " class X { /* comment */\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " class X { // comment\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " struct X {\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " union X {\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("extern \"C\" {\n"
- "void f() {\n"
- " return;\n"
- "}\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " class X {\n"
- " void f() { return; }\n"
- " } x;\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " [[nodiscard]] class X {\n"
- " void f() { return; }\n"
- " };\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " static class X {\n"
- " void f() { return; }\n"
- " } x;\n"
- "} // namespace",
- ShortInlineFunctions);
- verifyFormat("namespace {\n"
- " constexpr class X {\n"
- " void f() { return; }\n"
- " } x;\n"
- "} // namespace",
- ShortInlineFunctions);
-
- ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
- verifyFormat("extern \"C\" {\n"
- " void f() {\n"
- " return;\n"
- " }\n"
- "} // namespace",
- ShortInlineFunctions);
-
- Style.NamespaceIndentation = FormatStyle::NI_Inner;
- verifyFormat("namespace out {\n"
- "int i;\n"
- "namespace in {\n"
- " int i;\n"
- "} // namespace in\n"
- "} // namespace out",
- "namespace out {\n"
- "int i;\n"
- "namespace in {\n"
- "int i;\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
-
- Style.NamespaceIndentation = FormatStyle::NI_None;
- verifyFormat("template <class T>\n"
- "concept a_concept = X<>;\n"
- "namespace B {\n"
- "struct b_struct {};\n"
- "} // namespace B",
- Style);
- verifyFormat("template <int I>\n"
- "constexpr void foo()\n"
- " requires(I == 42)\n"
- "{}\n"
- "namespace ns {\n"
- "void foo() {}\n"
- "} // namespace ns",
- Style);
-
- FormatStyle LLVMWithCompactInnerNamespace = getLLVMStyle();
- LLVMWithCompactInnerNamespace.CompactNamespaces = true;
- LLVMWithCompactInnerNamespace.NamespaceIndentation = FormatStyle::NI_Inner;
- verifyFormat("namespace ns1 { namespace ns2 { namespace ns3 {\n"
- "// block for debug mode\n"
- "#ifndef NDEBUG\n"
- "#endif\n"
- "}}} // namespace ns1::ns2::ns3",
- LLVMWithCompactInnerNamespace);
-}
-
-TEST_F(FormatTest, NamespaceMacros) {
- FormatStyle Style = getLLVMStyle();
- Style.NamespaceMacros.push_back("TESTSUITE");
-
- verifyFormat("TESTSUITE(A) {\n"
- "int foo();\n"
- "} // TESTSUITE(A)",
- Style);
-
- verifyFormat("TESTSUITE(A, B) {\n"
- "int foo();\n"
- "} // TESTSUITE(A)",
- Style);
-
- // Properly indent according to NamespaceIndentation style
- Style.NamespaceIndentation = FormatStyle::NI_All;
- verifyFormat("TESTSUITE(A) {\n"
- " int foo();\n"
- "} // TESTSUITE(A)",
- Style);
- verifyFormat("TESTSUITE(A) {\n"
- " namespace B {\n"
- " int foo();\n"
- " } // namespace B\n"
- "} // TESTSUITE(A)",
- Style);
- verifyFormat("namespace A {\n"
- " TESTSUITE(B) {\n"
- " int foo();\n"
- " } // TESTSUITE(B)\n"
- "} // namespace A",
- Style);
-
- Style.NamespaceIndentation = FormatStyle::NI_Inner;
- verifyFormat("TESTSUITE(A) {\n"
- "TESTSUITE(B) {\n"
- " int foo();\n"
- "} // TESTSUITE(B)\n"
- "} // TESTSUITE(A)",
- Style);
- verifyFormat("TESTSUITE(A) {\n"
- "namespace B {\n"
- " int foo();\n"
- "} // namespace B\n"
- "} // TESTSUITE(A)",
- Style);
- verifyFormat("namespace A {\n"
- "TESTSUITE(B) {\n"
- " int foo();\n"
- "} // TESTSUITE(B)\n"
- "} // namespace A",
- Style);
-
- // Properly merge namespace-macros blocks in CompactNamespaces mode
- Style.NamespaceIndentation = FormatStyle::NI_None;
- Style.CompactNamespaces = true;
- verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
- "}} // TESTSUITE(A::B)",
- Style);
-
- verifyFormat("TESTSUITE(out) { TESTSUITE(in) {\n"
- "}} // TESTSUITE(out::in)",
- "TESTSUITE(out) {\n"
- "TESTSUITE(in) {\n"
- "} // TESTSUITE(in)\n"
- "} // TESTSUITE(out)",
- Style);
-
- verifyFormat("TESTSUITE(out) { TESTSUITE(in) {\n"
- "}} // TESTSUITE(out::in)",
- "TESTSUITE(out) {\n"
- "TESTSUITE(in) {\n"
- "} // TESTSUITE(in)\n"
- "} // TESTSUITE(out)",
- Style);
-
- // Do not merge different namespaces/macros
- verifyFormat("namespace out {\n"
- "TESTSUITE(in) {\n"
- "} // TESTSUITE(in)\n"
- "} // namespace out",
- Style);
- verifyFormat("TESTSUITE(out) {\n"
- "namespace in {\n"
- "} // namespace in\n"
- "} // TESTSUITE(out)",
- Style);
- Style.NamespaceMacros.push_back("FOOBAR");
- verifyFormat("TESTSUITE(out) {\n"
- "FOOBAR(in) {\n"
- "} // FOOBAR(in)\n"
- "} // TESTSUITE(out)",
- Style);
-}
-
-TEST_F(FormatTest, FormatsCompactNamespaces) {
- FormatStyle Style = getLLVMStyle();
- Style.CompactNamespaces = true;
- Style.NamespaceMacros.push_back("TESTSUITE");
-
- verifyFormat("namespace A { namespace B {\n"
- "}} // namespace A::B",
- Style);
-
- verifyFormat("namespace out { namespace in {\n"
- "}} // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
-
- // Only namespaces which have both consecutive opening and end get compacted
- verifyFormat("namespace out {\n"
- "namespace in1 {\n"
- "} // namespace in1\n"
- "namespace in2 {\n"
- "} // namespace in2\n"
- "} // namespace out",
- Style);
-
- verifyFormat("namespace out {\n"
- "int i;\n"
- "namespace in {\n"
- "int j;\n"
- "} // namespace in\n"
- "int k;\n"
- "} // namespace out",
- "namespace out { int i;\n"
- "namespace in { int j; } // namespace in\n"
- "int k; } // namespace out",
- Style);
-
- Style.ColumnLimit = 41;
- verifyFormat("namespace A { namespace B { namespace C {\n"
- "}}} // namespace A::B::C",
- "namespace A { namespace B {\n"
- "namespace C {\n"
- "}} // namespace B::C\n"
- "} // namespace A",
- Style);
-
- Style.ColumnLimit = 40;
- verifyFormat("namespace aaaaaaaaaa {\n"
- "namespace bbbbbbbbbb {\n"
- "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
- "namespace aaaaaaaaaa {\n"
- "namespace bbbbbbbbbb {\n"
- "} // namespace bbbbbbbbbb\n"
- "} // namespace aaaaaaaaaa",
- Style);
-
- verifyFormat("namespace aaaaaa { namespace bbbbbb {\n"
- "namespace cccccc {\n"
- "}}} // namespace aaaaaa::bbbbbb::cccccc",
- "namespace aaaaaa {\n"
- "namespace bbbbbb {\n"
- "namespace cccccc {\n"
- "} // namespace cccccc\n"
- "} // namespace bbbbbb\n"
- "} // namespace aaaaaa",
- Style);
-
- verifyFormat("namespace a { namespace b {\n"
- "namespace c {\n"
- "}}} // namespace a::b::c",
- Style);
-
- Style.ColumnLimit = 80;
-
- // Extra semicolon after 'inner' closing brace prevents merging
- verifyFormat("namespace out { namespace in {\n"
- "}; } // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "}; // namespace in\n"
- "} // namespace out",
- Style);
-
- // Extra semicolon after 'outer' closing brace is conserved
- verifyFormat("namespace out { namespace in {\n"
- "}}; // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "} // namespace in\n"
- "}; // namespace out",
- Style);
-
- Style.NamespaceIndentation = FormatStyle::NI_All;
- verifyFormat("namespace out { namespace in {\n"
- " int i;\n"
- "}} // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "int i;\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
- verifyFormat("namespace out { namespace mid {\n"
- " namespace in {\n"
- " int j;\n"
- " } // namespace in\n"
- " int k;\n"
- "}} // namespace out::mid",
- "namespace out { namespace mid {\n"
- "namespace in { int j; } // namespace in\n"
- "int k; }} // namespace out::mid",
- Style);
-
- verifyFormat("namespace A { namespace B { namespace C {\n"
- " int i;\n"
- "}}} // namespace A::B::C\n"
- "int main() {\n"
- " if (true)\n"
- " return 0;\n"
- "}",
- "namespace A { namespace B {\n"
- "namespace C {\n"
- " int i;\n"
- "}} // namespace B::C\n"
- "} // namespace A\n"
- "int main() {\n"
- " if (true)\n"
- " return 0;\n"
- "}",
- Style);
-
- verifyFormat("namespace A { namespace B { namespace C {\n"
- "#ifdef FOO\n"
- " int i;\n"
- "#endif\n"
- "}}} // namespace A::B::C\n"
- "int main() {\n"
- " if (true)\n"
- " return 0;\n"
- "}",
- "namespace A { namespace B {\n"
- "namespace C {\n"
- "#ifdef FOO\n"
- " int i;\n"
- "#endif\n"
- "}} // namespace B::C\n"
- "} // namespace A\n"
- "int main() {\n"
- " if (true)\n"
- " return 0;\n"
- "}",
- Style);
-
- Style.NamespaceIndentation = FormatStyle::NI_Inner;
- verifyFormat("namespace out { namespace in {\n"
- " int i;\n"
- "}} // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "int i;\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
- verifyFormat("namespace out { namespace mid { namespace in {\n"
- " int i;\n"
- "}}} // namespace out::mid::in",
- "namespace out {\n"
- "namespace mid {\n"
- "namespace in {\n"
- "int i;\n"
- "} // namespace in\n"
- "} // namespace mid\n"
- "} // namespace out",
- Style);
-
- Style.CompactNamespaces = true;
- Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.BeforeLambdaBody = true;
- verifyFormat("namespace out { namespace in {\n"
- "}} // namespace out::in",
- Style);
- verifyFormat("namespace out { namespace in {\n"
- "}} // namespace out::in",
- "namespace out {\n"
- "namespace in {\n"
- "} // namespace in\n"
- "} // namespace out",
- Style);
-}
-
-TEST_F(FormatTest, FormatsExternC) {
- verifyFormat("extern \"C\" {\nint a;");
- verifyFormat("extern \"C\" {}");
- verifyFormat("extern \"C\" {\n"
- "int foo();\n"
- "}");
- verifyFormat("extern \"C\" int foo() {}");
- verifyFormat("extern \"C\" int foo();");
- verifyFormat("extern \"C\" int foo() {\n"
- " int i = 42;\n"
- " return i;\n"
- "}");
- verifyFormat(
- "extern \"C\" char const *const\n"
- " OpenCL_source_OpenCLRunTime_test_attribute_opencl_unroll_hint;");
-
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- verifyFormat("extern \"C\" int foo() {}", Style);
- verifyFormat("extern \"C\" int foo();", Style);
- verifyFormat("extern \"C\" int foo()\n"
- "{\n"
- " int i = 42;\n"
- " return i;\n"
- "}",
- Style);
-
- Style.BraceWrapping.AfterExternBlock = true;
- Style.BraceWrapping.SplitEmptyRecord = false;
- verifyFormat("extern \"C\"\n"
- "{}",
- Style);
- verifyFormat("extern \"C\"\n"
- "{\n"
- " int foo();\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, IndentExternBlockStyle) {
- FormatStyle Style = getLLVMStyle();
- Style.IndentWidth = 2;
-
- Style.IndentExternBlock = FormatStyle::IEBS_Indent;
- verifyFormat("extern \"C\" { /*9*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\" {\n"
- " int foo10();\n"
- "}",
- Style);
-
- Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
- verifyFormat("extern \"C\" { /*11*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\" {\n"
- "int foo12();\n"
- "}",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("extern \"C\"\n"
- "{\n"
- "int i;\n"
- "}",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterExternBlock = true;
- Style.IndentExternBlock = FormatStyle::IEBS_Indent;
- verifyFormat("extern \"C\"\n"
- "{ /*13*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\"\n{\n"
- " int foo14();\n"
- "}",
- Style);
-
- Style.BraceWrapping.AfterExternBlock = false;
- Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
- verifyFormat("extern \"C\" { /*15*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\" {\n"
- "int foo16();\n"
- "}",
- Style);
-
- Style.BraceWrapping.AfterExternBlock = true;
- verifyFormat("extern \"C\"\n"
- "{ /*13*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\"\n"
- "{\n"
- "int foo14();\n"
- "}",
- Style);
-
- Style.IndentExternBlock = FormatStyle::IEBS_Indent;
- verifyFormat("extern \"C\"\n"
- "{ /*13*/\n"
- "}",
- Style);
- verifyFormat("extern \"C\"\n"
- "{\n"
- " int foo14();\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, FormatsInlineASM) {
- verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
- verifyFormat("asm(\"nop\" ::: \"memory\");");
- verifyFormat(
- "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
- " \"cpuid\\n\\t\"\n"
- " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
- " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
- " : \"a\"(value));");
- verifyFormat(
- "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
- " __asm {\n"
- " mov edx,[that] // vtable in edx\n"
- " mov eax,methodIndex\n"
- " call [edx][eax*4] // stdcall\n"
- " }\n"
- "}",
- "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
- " __asm {\n"
- " mov edx,[that] // vtable in edx\n"
- " mov eax,methodIndex\n"
- " call [edx][eax*4] // stdcall\n"
- " }\n"
- "}");
- verifyNoChange("_asm {\n"
- " xor eax, eax;\n"
- " cpuid;\n"
- "}");
- verifyFormat("void function() {\n"
- " // comment\n"
- " asm(\"\");\n"
- "}");
- verifyFormat("__asm {\n"
- "}\n"
- "int i;",
- "__asm {\n"
- "}\n"
- "int i;");
-
- auto Style = getLLVMStyleWithColumns(0);
- constexpr StringRef Code1(
- "asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
- constexpr StringRef Code2("asm(\"xyz\"\n"
- " : \"=a\"(a), \"=d\"(b)\n"
- " : \"a\"(data));");
- constexpr StringRef Code3("asm(\"xyz\" : \"=a\"(a), \"=d\"(b)\n"
- " : \"a\"(data));");
-
- Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
- verifyFormat(Code1, Style);
- verifyNoChange(Code2, Style);
- verifyNoChange(Code3, Style);
-
- Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Always;
- verifyFormat(Code2, Code1, Style);
- verifyNoChange(Code2, Style);
- verifyFormat(Code2, Code3, Style);
-}
-
-TEST_F(FormatTest, FormatTryCatch) {
- verifyFormat("try {\n"
- " throw a * b;\n"
- "} catch (int a) {\n"
- " // Do nothing.\n"
- "} catch (...) {\n"
- " exit(42);\n"
- "}");
-
- // Function-level try statements.
- verifyFormat("int f() try { return 4; } catch (...) {\n"
- " return 5;\n"
- "}");
- verifyFormat("class A {\n"
- " int a;\n"
- " A() try : a(0) {\n"
- " } catch (...) {\n"
- " throw;\n"
- " }\n"
- "};");
- verifyFormat("class A {\n"
- " int a;\n"
- " A() try : a(0), b{1} {\n"
- " } catch (...) {\n"
- " throw;\n"
- " }\n"
- "};");
- verifyFormat("class A {\n"
- " int a;\n"
- " A() try : a(0), b{1}, c{2} {\n"
- " } catch (...) {\n"
- " throw;\n"
- " }\n"
- "};");
- verifyFormat("class A {\n"
- " int a;\n"
- " A() try : a(0), b{1}, c{2} {\n"
- " { // New scope.\n"
- " }\n"
- " } catch (...) {\n"
- " throw;\n"
- " }\n"
- "};");
-
- // Incomplete try-catch blocks.
- verifyIncompleteFormat("try {} catch (");
-}
-
-TEST_F(FormatTest, FormatTryAsAVariable) {
- auto Style = getLLVMStyle(FormatStyle::LK_C);
- verifyFormat("int try;", Style);
- verifyFormat("int try, size;", Style);
- verifyFormat("try = foo();", Style);
-
- verifyFormat("if (try < size) {\n return true;\n}");
-
- verifyFormat("int catch;");
- verifyFormat("int catch, size;");
- verifyFormat("catch = foo();");
- verifyFormat("if (catch < size) {\n return true;\n}");
-
- Style.Language = FormatStyle::LK_Cpp;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- Style.BraceWrapping.BeforeCatch = true;
- verifyFormat("try {\n"
- " int bar = 1;\n"
- "}\n"
- "catch (...) {\n"
- " int bar = 1;\n"
- "}",
- Style);
- verifyFormat("#if NO_EX\n"
- "try\n"
- "#endif\n"
- "{\n"
- "}\n"
- "#if NO_EX\n"
- "catch (...) {\n"
- "}",
- Style);
- verifyFormat("try /* abc */ {\n"
- " int bar = 1;\n"
- "}\n"
- "catch (...) {\n"
- " int bar = 1;\n"
- "}",
- Style);
- verifyFormat("try\n"
- "// abc\n"
- "{\n"
- " int bar = 1;\n"
- "}\n"
- "catch (...) {\n"
- " int bar = 1;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, FormatSEHTryCatch) {
- verifyFormat("__try {\n"
- " int a = b * c;\n"
- "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
- " // Do nothing.\n"
- "}");
-
- verifyFormat("__try {\n"
- " int a = b * c;\n"
- "} __finally {\n"
- " // Do nothing.\n"
- "}");
-
- verifyFormat("DEBUG({\n"
- " __try {\n"
- " } __finally {\n"
- " }\n"
- "});");
-}
-
-TEST_F(FormatTest, IncompleteTryCatchBlocks) {
- verifyFormat("try {\n"
- " f();\n"
- "} catch {\n"
- " g();\n"
- "}");
- verifyFormat("try {\n"
- " f();\n"
- "} catch (A a) MACRO(x) {\n"
- " g();\n"
- "} catch (B b) MACRO(x) {\n"
- " g();\n"
- "}");
-}
-
-TEST_F(FormatTest, FormatTryCatchBraceStyles) {
- FormatStyle Style = getLLVMStyle();
- for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
- FormatStyle::BS_WebKit}) {
- Style.BreakBeforeBraces = BraceStyle;
- verifyFormat("try {\n"
- " // something\n"
- "} catch (...) {\n"
- " // something\n"
- "}",
- Style);
- }
- Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
- verifyFormat("try {\n"
- " // something\n"
- "}\n"
- "catch (...) {\n"
- " // something\n"
- "}",
- Style);
- verifyFormat("__try {\n"
- " // something\n"
- "}\n"
- "__finally {\n"
- " // something\n"
- "}",
- Style);
- verifyFormat("@try {\n"
- " // something\n"
- "}\n"
- "@finally {\n"
- " // something\n"
- "}",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("try\n"
- "{\n"
- " // something\n"
- "}\n"
- "catch (...)\n"
- "{\n"
- " // something\n"
- "}",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
- verifyFormat("try\n"
- " {\n"
- " // something white\n"
- " }\n"
- "catch (...)\n"
- " {\n"
- " // something white\n"
- " }",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_GNU;
- verifyFormat("try\n"
- " {\n"
- " // something\n"
- " }\n"
- "catch (...)\n"
- " {\n"
- " // something\n"
- " }",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.BeforeCatch = true;
- verifyFormat("try {\n"
- " // something\n"
- "}\n"
- "catch (...) {\n"
- " // something\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, StaticInitializers) {
- verifyFormat("static SomeClass SC = {1, 'a'};");
-
- verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
- " 100000000, "
- "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
-
- // Here, everything other than the "}" would fit on a line.
- verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
- " 10000000000000000000000000};");
- verifyFormat("S s = {a,\n"
- "\n"
- " b};",
- "S s = {\n"
- " a,\n"
- "\n"
- " b\n"
- "};");
-
- // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
- // line. However, the formatting looks a bit off and this probably doesn't
- // happen often in practice.
- verifyFormat("static int Variable[1] = {\n"
- " {1000000000000000000000000000000000000}};",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, DesignatedInitializers) {
- verifyFormat("const struct A a = {.a = 1, .b = 2};");
- verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
- " .bbbbbbbbbb = 2,\n"
- " .cccccccccc = 3,\n"
- " .dddddddddd = 4,\n"
- " .eeeeeeeeee = 5};");
- verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
- " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
- " .ccccccccccccccccccccccccccc = 3,\n"
- " .ddddddddddddddddddddddddddd = 4,\n"
- " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
-
- verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
-
- verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
- verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
- " [2] = bbbbbbbbbb,\n"
- " [3] = cccccccccc,\n"
- " [4] = dddddddddd,\n"
- " [5] = eeeeeeeeee};");
- verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
- " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
- " [3] = cccccccccccccccccccccccccccccccccccccc,\n"
- " [4] = dddddddddddddddddddddddddddddddddddddd,\n"
- " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
-
- verifyFormat("for (const TestCase &test_case : {\n"
- " TestCase{\n"
- " .a = 1,\n"
- " .b = 1,\n"
- " },\n"
- " TestCase{\n"
- " .a = 2,\n"
- " .b = 2,\n"
- " },\n"
- " }) {\n"
- "}");
-}
-
-TEST_F(FormatTest, BracedInitializerIndentWidth) {
- auto Style = getLLVMStyleWithColumns(60);
- Style.BinPackArguments = true;
- Style.BreakAfterOpenBracketFunction = true;
- Style.BreakAfterOpenBracketBracedList = true;
- Style.BracedInitializerIndentWidth = 6;
-
- // Non-initializing braces are unaffected by BracedInitializerIndentWidth.
- verifyFormat("enum class {\n"
- " One,\n"
- " Two,\n"
- "};",
- Style);
- verifyFormat("class Foo {\n"
- " Foo() {}\n"
- " void bar();\n"
- "};",
- Style);
- verifyFormat("void foo() {\n"
- " auto bar = baz;\n"
- " return baz;\n"
- "};",
- Style);
- verifyFormat("auto foo = [&] {\n"
- " auto bar = baz;\n"
- " return baz;\n"
- "};",
- Style);
- verifyFormat("{\n"
- " auto bar = baz;\n"
- " return baz;\n"
- "};",
- Style);
- // Non-brace initialization is unaffected by BracedInitializerIndentWidth.
- verifyFormat("SomeClass clazz(\n"
- " \"xxxxxxxxxxxxxxxxxx\", \"yyyyyyyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzzzzzzz\");",
- Style);
-
- // The following types of initialization are all affected by
- // BracedInitializerIndentWidth. Aggregate initialization.
- verifyFormat("int LooooooooooooooooooooooooongVariable[2] = {\n"
- " 10000000, 20000000};",
- Style);
- verifyFormat("SomeStruct s{\n"
- " \"xxxxxxxxxxxxxxxx\", \"yyyyyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzzzzz\"};",
- Style);
- // Designated initializers.
- verifyFormat("int LooooooooooooooooooooooooongVariable[2] = {\n"
- " [0] = 10000000, [1] = 20000000};",
- Style);
- verifyFormat("SomeStruct s{\n"
- " .foo = \"xxxxxxxxxxxxx\",\n"
- " .bar = \"yyyyyyyyyyyyy\",\n"
- " .baz = \"zzzzzzzzzzzzz\"};",
- Style);
- // List initialization.
- verifyFormat("SomeStruct s{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- verifyFormat("SomeStruct{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- verifyFormat("new SomeStruct{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Member initializer.
- verifyFormat("class SomeClass {\n"
- " SomeStruct s{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- " };\n"
- "};",
- Style);
- // Constructor member initializer.
- verifyFormat("SomeClass::SomeClass : strct{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- " } {}",
- Style);
- // Copy initialization.
- verifyFormat("SomeStruct s = SomeStruct{\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Copy list initialization.
- verifyFormat("SomeStruct s = {\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Assignment operand initialization.
- verifyFormat("s = {\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Returned object initialization.
- verifyFormat("return {\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Initializer list.
- verifyFormat("auto initializerList = {\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "};",
- Style);
- // Function parameter initialization.
- verifyFormat("func({\n"
- " \"xxxxxxxxxxxxx\",\n"
- " \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\",\n"
- "});",
- Style);
- // Nested init lists.
- verifyFormat("SomeStruct s = {\n"
- " {{init1, init2, init3, init4, init5},\n"
- " {init1, init2, init3, init4, init5}}};",
- Style);
- verifyFormat("SomeStruct s = {\n"
- " {{\n"
- " .init1 = 1,\n"
- " .init2 = 2,\n"
- " .init3 = 3,\n"
- " .init4 = 4,\n"
- " .init5 = 5,\n"
- " },\n"
- " {init1, init2, init3, init4, init5}}};",
- Style);
- verifyFormat("SomeArrayT a[3] = {\n"
- " {\n"
- " foo,\n"
- " bar,\n"
- " },\n"
- " {\n"
- " foo,\n"
- " bar,\n"
- " },\n"
- " SomeArrayT{},\n"
- "};",
- Style);
- verifyFormat("SomeArrayT a[3] = {\n"
- " {foo},\n"
- " {\n"
- " {\n"
- " init1,\n"
- " init2,\n"
- " init3,\n"
- " },\n"
- " {\n"
- " init1,\n"
- " init2,\n"
- " init3,\n"
- " },\n"
- " },\n"
- " {baz},\n"
- "};",
- Style);
-
- // Aligning after open braces unaffected by BracedInitializerIndentWidth.
- Style.AlignAfterOpenBracket = true;
- Style.BreakAfterOpenBracketBracedList = false;
- verifyFormat("SomeStruct s{\"xxxxxxxxxxxxx\", \"yyyyyyyyyyyyy\",\n"
- " \"zzzzzzzzzzzzz\"};",
- Style);
-}
-
-TEST_F(FormatTest, NestedStaticInitializers) {
- verifyFormat("static A x = {{{}}};");
- verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
- " {init1, init2, init3, init4}}};",
- getLLVMStyleWithColumns(50));
-
- verifyFormat("somes Status::global_reps[3] = {\n"
- " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
- " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
- " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
- getLLVMStyleWithColumns(60));
- verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
- " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
- " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
- " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
- verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
- " {rect.fRight - rect.fLeft, rect.fBottom - "
- "rect.fTop}};");
-
- verifyFormat(
- "SomeArrayOfSomeType a = {\n"
- " {{1, 2, 3},\n"
- " {1, 2, 3},\n"
- " {111111111111111111111111111111, 222222222222222222222222222222,\n"
- " 333333333333333333333333333333},\n"
- " {1, 2, 3},\n"
- " {1, 2, 3}}};");
- verifyFormat(
- "SomeArrayOfSomeType a = {\n"
- " {{1, 2, 3}},\n"
- " {{1, 2, 3}},\n"
- " {{111111111111111111111111111111, 222222222222222222222222222222,\n"
- " 333333333333333333333333333333}},\n"
- " {{1, 2, 3}},\n"
- " {{1, 2, 3}}};");
-
- verifyFormat("struct {\n"
- " unsigned bit;\n"
- " const char *const name;\n"
- "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
- " {kOsWin, \"Windows\"},\n"
- " {kOsLinux, \"Linux\"},\n"
- " {kOsCrOS, \"Chrome OS\"}};");
- verifyFormat("struct {\n"
- " unsigned bit;\n"
- " const char *const name;\n"
- "} kBitsToOs[] = {\n"
- " {kOsMac, \"Mac\"},\n"
- " {kOsWin, \"Windows\"},\n"
- " {kOsLinux, \"Linux\"},\n"
- " {kOsCrOS, \"Chrome OS\"},\n"
- "};");
-}
-
-TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
- verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
- " \\\n"
- " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
-}
-
-TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
- verifyFormat("virtual void write(ELFWriter *writerrr,\n"
- " OwningPtr<FileOutputBuffer> &buffer) = 0;");
-
- // Do break defaulted and deleted functions.
- verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
- " default;",
- getLLVMStyleWithColumns(40));
- verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
- " delete;",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
- verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
- getLLVMStyleWithColumns(40));
- verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
- getLLVMStyleWithColumns(40));
- verifyFormat("#define Q \\\n"
- " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n"
- " \"aaaaaaaa.cpp\"",
- "#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, UnderstandsLinePPDirective) {
- verifyFormat("# 123 \"A string literal\"",
- " # 123 \"A string literal\"");
-}
-
-TEST_F(FormatTest, LayoutUnknownPPDirective) {
- verifyFormat("#;");
- verifyFormat("#\n;\n;\n;");
-}
-
-TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
- verifyFormat("#line 42 \"test\"", "# \\\n line \\\n 42 \\\n \"test\"");
- verifyFormat("#define A B", "# \\\n define \\\n A \\\n B",
- getLLVMStyleWithColumns(12));
-}
-
-TEST_F(FormatTest, EndOfFileEndsPPDirective) {
- verifyFormat("#line 42 \"test\"", "# \\\n line \\\n 42 \\\n \"test\"");
- verifyFormat("#define A B", "# \\\n define \\\n A \\\n B");
-}
-
-TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
- verifyFormat("#define A \\x20");
- verifyFormat("#define A \\ x20");
- verifyFormat("#define A \\ x20", "#define A \\ x20");
- verifyFormat("#define A ''");
- verifyFormat("#define A ''qqq");
- verifyFormat("#define A `qqq");
- verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
- verifyFormat("const char *c = STRINGIFY(\n"
- "\\na : b);",
- "const char * c = STRINGIFY(\n"
- "\\na : b);");
-
- verifyFormat("a\r\\");
- verifyFormat("a\v\\");
- verifyFormat("a\f\\");
-}
-
-TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
- FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
- style.IndentWidth = 4;
- style.PPIndentWidth = 1;
-
- style.IndentPPDirectives = FormatStyle::PPDIS_None;
- verifyFormat("#ifdef __linux__\n"
- "void foo() {\n"
- " int x = 0;\n"
- "}\n"
- "#define FOO\n"
- "#endif\n"
- "void bar() {\n"
- " int y = 0;\n"
- "}",
- style);
-
- style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
- verifyFormat("#ifdef __linux__\n"
- "void foo() {\n"
- " int x = 0;\n"
- "}\n"
- "# define FOO foo\n"
- "#endif\n"
- "void bar() {\n"
- " int y = 0;\n"
- "}",
- style);
-
- style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
- verifyFormat("#ifdef __linux__\n"
- "void foo() {\n"
- " int x = 0;\n"
- "}\n"
- " #define FOO foo\n"
- "#endif\n"
- "void bar() {\n"
- " int y = 0;\n"
- "}",
- style);
- verifyFormat("#if 1\n"
- " // some comments\n"
- " // another\n"
- " #define foo 1\n"
- "// not a define comment\n"
- "void bar() {\n"
- " // comment\n"
- " int y = 0;\n"
- "}",
- "#if 1\n"
- "// some comments\n"
- "// another\n"
- "#define foo 1\n"
- "// not a define comment\n"
- "void bar() {\n"
- " // comment\n"
- " int y = 0;\n"
- "}",
- style);
-
- style.IndentPPDirectives = FormatStyle::PPDIS_None;
- verifyFormat("#ifdef foo\n"
- "#define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
- verifyFormat("if (emacs) {\n"
- "#ifdef is\n"
- "#define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}",
- style);
- verifyFormat("#if abc\n"
- "#ifdef foo\n"
- "#define bar() \\\n"
- " if (A) { \\\n"
- " if (B) { \\\n"
- " C(); \\\n"
- " } \\\n"
- " } \\\n"
- " D();\n"
- "#endif\n"
- "#endif",
- style);
- verifyFormat("#ifndef foo\n"
- "#define foo\n"
- "if (emacs) {\n"
- "#ifdef is\n"
- "#define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}\n"
- "#endif",
- style);
- verifyFormat("#if 1\n"
- "#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }\n"
- "#endif",
- style);
- verifyFormat("#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }",
- style);
-
- style.PPIndentWidth = 2;
- verifyFormat("#ifdef foo\n"
- "#define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
- style.IndentWidth = 8;
- verifyFormat("#ifdef foo\n"
- "#define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
-
- style.IndentWidth = 1;
- style.PPIndentWidth = 4;
- verifyFormat("#if 1\n"
- "#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }\n"
- "#endif",
- style);
- verifyFormat("#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }",
- style);
-
- style.IndentPPDirectives = FormatStyle::PPDIS_Leave;
- style.IndentWidth = 4;
- verifyNoChange("#ifndef foo\n"
- "#define foo\n"
- "if (emacs) {\n"
- "#ifdef is\n"
- "#define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}\n"
- "#endif",
- style);
- verifyNoChange("#ifndef foo\n"
- " #define foo\n"
- "if (emacs) {\n"
- " #ifdef is\n"
- "#define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- " #endif\n"
- "}\n"
- "#endif",
- style);
- verifyNoChange(" #ifndef foo\n"
- "# define foo\n"
- "if (emacs) {\n"
- "#ifdef is\n"
- " # define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}\n"
- " #endif",
- style);
- verifyNoChange("#ifdef foo\n"
- "#else\n"
- "/* This is a comment */\n"
- "#ifdef BAR\n"
- "#endif\n"
- "#endif",
- style);
-
- style.IndentWidth = 1;
- style.PPIndentWidth = 4;
- verifyNoChange("# if 1\n"
- " #define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }\n"
- "# endif",
- style);
-
- style.IndentWidth = 4;
- style.PPIndentWidth = 1;
- style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
- verifyFormat("#ifdef foo\n"
- "# define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
- verifyFormat("#if abc\n"
- "# ifdef foo\n"
- "# define bar() \\\n"
- " if (A) { \\\n"
- " if (B) { \\\n"
- " C(); \\\n"
- " } \\\n"
- " } \\\n"
- " D();\n"
- "# endif\n"
- "#endif",
- style);
- verifyFormat("#ifndef foo\n"
- "#define foo\n"
- "if (emacs) {\n"
- "#ifdef is\n"
- "# define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}\n"
- "#endif",
- style);
- verifyFormat("#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }",
- style);
-
- style.PPIndentWidth = 2;
- style.IndentWidth = 8;
- verifyFormat("#ifdef foo\n"
- "# define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
-
- style.PPIndentWidth = 4;
- style.IndentWidth = 1;
- verifyFormat("#define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }",
- style);
-
- style.IndentWidth = 4;
- style.PPIndentWidth = 1;
- style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
- verifyFormat("if (emacs) {\n"
- "#ifdef is\n"
- " #define lit \\\n"
- " if (af) { \\\n"
- " return duh(); \\\n"
- " }\n"
- "#endif\n"
- "}",
- style);
- verifyFormat("#if abc\n"
- " #ifdef foo\n"
- " #define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- " #endif\n"
- "#endif",
- style);
- verifyFormat("#if 1\n"
- " #define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }\n"
- "#endif",
- style);
-
- style.PPIndentWidth = 2;
- verifyFormat("#ifdef foo\n"
- " #define bar() \\\n"
- " if (A) { \\\n"
- " B(); \\\n"
- " } \\\n"
- " C();\n"
- "#endif",
- style);
-
- style.PPIndentWidth = 4;
- style.IndentWidth = 1;
- verifyFormat("#if 1\n"
- " #define X \\\n"
- " { \\\n"
- " x; \\\n"
- " x; \\\n"
- " }\n"
- "#endif",
- style);
-}
-
-TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
- verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
- verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12));
- verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12));
- // FIXME: We never break before the macro name.
- verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12));
-
- verifyFormat("#define A A\n#define A A");
- verifyFormat("#define A(X) A\n#define A A");
-
- verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
- verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22));
-}
-
-TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
- verifyFormat("// somecomment\n"
- "#include \"a.h\"\n"
- "#define A( \\\n"
- " A, B)\n"
- "#include \"b.h\"\n"
- "// somecomment",
- " // somecomment\n"
- " #include \"a.h\"\n"
- "#define A(A,\\\n"
- " B)\n"
- " #include \"b.h\"\n"
- " // somecomment",
- getLLVMStyleWithColumns(13));
-}
-
-TEST_F(FormatTest, LayoutSingleHash) { verifyFormat("#\na;"); }
-
-TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
- verifyFormat("#define A \\\n"
- " c; \\\n"
- " e;\n"
- "f;",
- "#define A c; e;\n"
- "f;",
- getLLVMStyleWithColumns(14));
-}
-
-TEST_F(FormatTest, LayoutRemainingTokens) {
- verifyFormat("{\n"
- "}");
-}
-
-TEST_F(FormatTest, MacroDefinitionInsideStatement) {
- verifyFormat("int x,\n"
- "#define A\n"
- " y;",
- "int x,\n#define A\ny;");
-}
-
-TEST_F(FormatTest, HashInMacroDefinition) {
- verifyFormat("#define A(c) L#c");
- verifyFormat("#define A(c) u#c");
- verifyFormat("#define A(c) U#c");
- verifyFormat("#define A(c) u8#c");
- verifyFormat("#define A(c) LR#c");
- verifyFormat("#define A(c) uR#c");
- verifyFormat("#define A(c) UR#c");
- verifyFormat("#define A(c) u8R#c");
- verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11));
- verifyFormat("#define A \\\n"
- " { \\\n"
- " f(#c); \\\n"
- " }",
- getLLVMStyleWithColumns(11));
-
- verifyFormat("#define A(X) \\\n"
- " void function##X()",
- getLLVMStyleWithColumns(22));
-
- verifyFormat("#define A(a, b, c) \\\n"
- " void a##b##c()",
- getLLVMStyleWithColumns(22));
-
- verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
-
- verifyFormat("{\n"
- " {\n"
- "#define GEN_ID(_x) char *_x{#_x}\n"
- " GEN_ID(one);\n"
- " }\n"
- "}");
-}
-
-TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
- verifyFormat("#define A (x)");
- verifyFormat("#define A(x)");
-
- FormatStyle Style = getLLVMStyle();
- Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
- verifyFormat("#define true ((foo)1)", Style);
- Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
- verifyFormat("#define false((foo)0)", Style);
-}
-
-TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
- verifyFormat("#define A b;",
- "#define A \\\n"
- " \\\n"
- " b;",
- getLLVMStyleWithColumns(25));
- verifyNoChange("#define A \\\n"
- " \\\n"
- " a; \\\n"
- " b;",
- getLLVMStyleWithColumns(11));
- verifyNoChange("#define A \\\n"
- " a; \\\n"
- " \\\n"
- " b;",
- getLLVMStyleWithColumns(11));
-}
-
-TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
- verifyIncompleteFormat("#define A :");
- verifyFormat("#define SOMECASES \\\n"
- " case 1: \\\n"
- " case 2",
- getLLVMStyleWithColumns(20));
- verifyFormat("#define MACRO(a) \\\n"
- " if (a) \\\n"
- " f(); \\\n"
- " else \\\n"
- " g()",
- getLLVMStyleWithColumns(18));
- verifyFormat("#define A template <typename T>");
- verifyIncompleteFormat("#define STR(x) #x\n"
- "f(STR(this_is_a_string_literal{));");
- verifyFormat("#pragma omp threadprivate( \\\n"
- " y)), // expected-warning",
- getLLVMStyleWithColumns(28));
- verifyFormat("#d, = };");
- verifyFormat("#if \"a");
- verifyIncompleteFormat("({\n"
- "#define b \\\n"
- " } \\\n"
- " a\n"
- "a",
- getLLVMStyleWithColumns(15));
- verifyFormat("#define A \\\n"
- " { \\\n"
- " {\n"
- "#define B \\\n"
- " } \\\n"
- " }",
- getLLVMStyleWithColumns(15));
- verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
- verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
- verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
- verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}");
- verifyNoCrash("#else\n"
- "#else\n"
- "#endif\n"
- "#endif");
- verifyNoCrash("#else\n"
- "#if X\n"
- "#endif\n"
- "#endif");
- verifyNoCrash("#else\n"
- "#endif\n"
- "#if X\n"
- "#endif");
- verifyNoCrash("#if X\n"
- "#else\n"
- "#else\n"
- "#endif\n"
- "#endif");
- verifyNoCrash("#if X\n"
- "#elif Y\n"
- "#elif Y\n"
- "#endif\n"
- "#endif");
- verifyNoCrash("#endif\n"
- "#endif");
- verifyNoCrash("#endif\n"
- "#else");
- verifyNoCrash("#endif\n"
- "#elif Y");
-}
-
-TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
- verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
- verifyFormat("class A : public QObject {\n"
- " Q_OBJECT\n"
- "\n"
- " A() {}\n"
- "};",
- "class A : public QObject {\n"
- " Q_OBJECT\n"
- "\n"
- " A() {\n}\n"
- "} ;");
- verifyFormat("MACRO\n"
- "/*static*/ int i;",
- "MACRO\n"
- " /*static*/ int i;");
- verifyFormat("SOME_MACRO\n"
- "namespace {\n"
- "void f();\n"
- "} // namespace",
- "SOME_MACRO\n"
- " namespace {\n"
- "void f( );\n"
- "} // namespace");
- // Only if the identifier contains at least 5 characters.
- verifyFormat("HTTP f();", "HTTP\nf();");
- verifyNoChange("MACRO\nf();");
- // Only if everything is upper case.
- verifyFormat("class A : public QObject {\n"
- " Q_Object A() {}\n"
- "};",
- "class A : public QObject {\n"
- " Q_Object\n"
- " A() {\n}\n"
- "} ;");
-
- // Only if the next line can actually start an unwrapped line.
- verifyFormat("SOME_WEIRD_LOG_MACRO << SomeThing;", "SOME_WEIRD_LOG_MACRO\n"
- "<< SomeThing;");
-
- verifyFormat("GGGG(ffff(xxxxxxxxxxxxxxxxxxxx)->yyyyyyyyyyyyyyyyyyyy)(foo);",
- "GGGG(ffff(xxxxxxxxxxxxxxxxxxxx)->yyyyyyyyyyyyyyyyyyyy)\n"
- "(foo);",
- getLLVMStyleWithColumns(60));
-
- verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
- "(n, buffers))",
- getChromiumStyle(FormatStyle::LK_Cpp));
-
- // See PR41483
- verifyNoChange("/**/ FOO(a)\n"
- "FOO(b)");
-}
-
-TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
- verifyFormat("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
- "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
- "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
- "class X {};\n"
- "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
- "int *createScopDetectionPass() { return 0; }",
- " INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
- " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
- " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
- " class X {};\n"
- " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
- " int *createScopDetectionPass() { return 0; }");
- // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
- // braces, so that inner block is indented one level more.
- verifyFormat("int q() {\n"
- " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
- " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
- " IPC_END_MESSAGE_MAP()\n"
- "}",
- "int q() {\n"
- " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
- " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
- " IPC_END_MESSAGE_MAP()\n"
- "}");
-
- // Same inside macros.
- verifyFormat("#define LIST(L) \\\n"
- " L(A) \\\n"
- " L(B) \\\n"
- " L(C)",
- "#define LIST(L) \\\n"
- " L(A) \\\n"
- " L(B) \\\n"
- " L(C)",
- getGoogleStyle());
-
- // These must not be recognized as macros.
- verifyFormat("int q() {\n"
- " f(x);\n"
- " f(x) {}\n"
- " f(x)->g();\n"
- " f(x)->*g();\n"
- " f(x).g();\n"
- " f(x) = x;\n"
- " f(x) += x;\n"
- " f(x) -= x;\n"
- " f(x) *= x;\n"
- " f(x) /= x;\n"
- " f(x) %= x;\n"
- " f(x) &= x;\n"
- " f(x) |= x;\n"
- " f(x) ^= x;\n"
- " f(x) >>= x;\n"
- " f(x) <<= x;\n"
- " f(x)[y].z();\n"
- " LOG(INFO) << x;\n"
- " ifstream(x) >> x;\n"
- "}",
- "int q() {\n"
- " f(x)\n;\n"
- " f(x)\n {}\n"
- " f(x)\n->g();\n"
- " f(x)\n->*g();\n"
- " f(x)\n.g();\n"
- " f(x)\n = x;\n"
- " f(x)\n += x;\n"
- " f(x)\n -= x;\n"
- " f(x)\n *= x;\n"
- " f(x)\n /= x;\n"
- " f(x)\n %= x;\n"
- " f(x)\n &= x;\n"
- " f(x)\n |= x;\n"
- " f(x)\n ^= x;\n"
- " f(x)\n >>= x;\n"
- " f(x)\n <<= x;\n"
- " f(x)\n[y].z();\n"
- " LOG(INFO)\n << x;\n"
- " ifstream(x)\n >> x;\n"
- "}");
- verifyFormat("int q() {\n"
- " F(x)\n"
- " if (1) {\n"
- " }\n"
- " F(x)\n"
- " while (1) {\n"
- " }\n"
- " F(x)\n"
- " G(x);\n"
- " F(x)\n"
- " try {\n"
- " Q();\n"
- " } catch (...) {\n"
- " }\n"
- "}",
- "int q() {\n"
- "F(x)\n"
- "if (1) {}\n"
- "F(x)\n"
- "while (1) {}\n"
- "F(x)\n"
- "G(x);\n"
- "F(x)\n"
- "try { Q(); } catch (...) {}\n"
- "}");
- verifyFormat("class A {\n"
- " A() : t(0) {}\n"
- " A(int i) noexcept() : {}\n"
- " A(X x)\n" // FIXME: function-level try blocks are broken.
- " try : t(0) {\n"
- " } catch (...) {\n"
- " }\n"
- "};",
- "class A {\n"
- " A()\n : t(0) {}\n"
- " A(int i)\n noexcept() : {}\n"
- " A(X x)\n"
- " try : t(0) {} catch (...) {}\n"
- "};");
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- Style.BraceWrapping.AfterFunction = true;
- verifyFormat("void f()\n"
- "try\n"
- "{\n"
- "}",
- "void f() try {\n"
- "}",
- Style);
- verifyFormat("class SomeClass {\n"
- "public:\n"
- " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
- "};",
- "class SomeClass {\n"
- "public:\n"
- " SomeClass()\n"
- " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
- "};");
- verifyFormat("class SomeClass {\n"
- "public:\n"
- " SomeClass()\n"
- " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
- "};",
- "class SomeClass {\n"
- "public:\n"
- " SomeClass()\n"
- " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
- "};",
- getLLVMStyleWithColumns(40));
-
- verifyFormat("MACRO(>)");
-
- // Some macros contain an implicit semicolon.
- Style = getLLVMStyle();
- Style.StatementMacros.push_back("FOO");
- verifyFormat("FOO(a) int b = 0;");
- verifyFormat("FOO(a)\n"
- "int b = 0;",
- Style);
- verifyFormat("FOO(a);\n"
- "int b = 0;",
- Style);
- verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
- "int b = 0;",
- Style);
- verifyFormat("FOO()\n"
- "int b = 0;",
- Style);
- verifyFormat("FOO\n"
- "int b = 0;",
- Style);
- verifyFormat("void f() {\n"
- " FOO(a)\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("FOO(a)\n"
- "FOO(b)",
- Style);
- verifyFormat("int a = 0;\n"
- "FOO(b)\n"
- "int c = 0;",
- Style);
- verifyFormat("int a = 0;\n"
- "int x = FOO(a)\n"
- "int b = 0;",
- Style);
- verifyFormat("void foo(int a) { FOO(a) }\n"
- "uint32_t bar() {}",
- Style);
-}
-
-TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
- FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
-
- verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
- ZeroColumn);
-}
-
-TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
- verifyFormat("#define A \\\n"
- " f({ \\\n"
- " g(); \\\n"
- " });",
- getLLVMStyleWithColumns(11));
-}
-
-TEST_F(FormatTest, IndentPreprocessorDirectives) {
- FormatStyle Style = getLLVMStyleWithColumns(40);
- Style.IndentPPDirectives = FormatStyle::PPDIS_None;
- verifyFormat("#ifdef _WIN32\n"
- "#define A 0\n"
- "#ifdef VAR2\n"
- "#define B 1\n"
- "#include <someheader.h>\n"
- "#define MACRO \\\n"
- " some_very_long_func_aaaaaaaaaa();\n"
- "#endif\n"
- "#else\n"
- "#define A 1\n"
- "#endif",
- Style);
- Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
- verifyFormat("#if 1\n"
- "# define __STR(x) #x\n"
- "#endif",
- Style);
- verifyFormat("#ifdef _WIN32\n"
- "# define A 0\n"
- "# ifdef VAR2\n"
- "# define B 1\n"
- "# include <someheader.h>\n"
- "# define MACRO \\\n"
- " some_very_long_func_aaaaaaaaaa();\n"
- "# endif\n"
- "#else\n"
- "# define A 1\n"
- "#endif",
- Style);
- verifyFormat("#if A\n"
- "# define MACRO \\\n"
- " void a(int x) { \\\n"
- " b(); \\\n"
- " c(); \\\n"
- " d(); \\\n"
- " e(); \\\n"
- " f(); \\\n"
- " }\n"
- "#endif",
- Style);
- // Comments before include guard.
- verifyFormat("// file comment\n"
- "// file comment\n"
- "#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "code();\n"
- "#endif",
- Style);
- // Test with include guards.
- verifyFormat("#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "code();\n"
- "#endif",
- Style);
- // Include guards must have a #define with the same variable immediately
- // after #ifndef.
- verifyFormat("#ifndef NOT_GUARD\n"
- "# define FOO\n"
- "code();\n"
- "#endif",
- Style);
-
- // Include guards must cover the entire file.
- verifyFormat("code();\n"
- "code();\n"
- "#ifndef NOT_GUARD\n"
- "# define NOT_GUARD\n"
- "code();\n"
- "#endif",
- Style);
- verifyFormat("#ifndef NOT_GUARD\n"
- "# define NOT_GUARD\n"
- "code();\n"
- "#endif\n"
- "code();",
- Style);
- // Test with trailing blank lines.
- verifyFormat("#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "code();\n"
- "#endif",
- Style);
- // Include guards don't have #else.
- verifyFormat("#ifndef NOT_GUARD\n"
- "# define NOT_GUARD\n"
- "code();\n"
- "#else\n"
- "#endif",
- Style);
- verifyFormat("#ifndef NOT_GUARD\n"
- "# define NOT_GUARD\n"
- "code();\n"
- "#elif FOO\n"
- "#endif",
- Style);
- // Non-identifier #define after potential include guard.
- verifyFormat("#ifndef FOO\n"
- "# define 1\n"
- "#endif",
- Style);
- // #if closes past last non-preprocessor line.
- verifyFormat("#ifndef FOO\n"
- "#define FOO\n"
- "#if 1\n"
- "int i;\n"
- "# define A 0\n"
- "#endif\n"
- "#endif",
- Style);
- // Don't crash if there is an #elif directive without a condition.
- verifyFormat("#if 1\n"
- "int x;\n"
- "#elif\n"
- "int y;\n"
- "#else\n"
- "int z;\n"
- "#endif",
- Style);
- // FIXME: This doesn't handle the case where there's code between the
- // #ifndef and #define but all other conditions hold. This is because when
- // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
- // previous code line yet, so we can't detect it.
- verifyFormat("#ifndef NOT_GUARD\n"
- "code();\n"
- "#define NOT_GUARD\n"
- "code();\n"
- "#endif",
- "#ifndef NOT_GUARD\n"
- "code();\n"
- "# define NOT_GUARD\n"
- "code();\n"
- "#endif",
- Style);
- // FIXME: This doesn't handle cases where legitimate preprocessor lines may
- // be outside an include guard. Examples are #pragma once and
- // #pragma GCC diagnostic, or anything else that does not change the meaning
- // of the file if it's included multiple times.
- verifyFormat("#ifdef WIN32\n"
- "# pragma once\n"
- "#endif\n"
- "#ifndef HEADER_H\n"
- "# define HEADER_H\n"
- "code();\n"
- "#endif",
- "#ifdef WIN32\n"
- "# pragma once\n"
- "#endif\n"
- "#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "code();\n"
- "#endif",
- Style);
- // FIXME: This does not detect when there is a single non-preprocessor line
- // in front of an include-guard-like structure where other conditions hold
- // because ScopedLineState hides the line.
- verifyFormat("code();\n"
- "#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "code();\n"
- "#endif",
- "code();\n"
- "#ifndef HEADER_H\n"
- "# define HEADER_H\n"
- "code();\n"
- "#endif",
- Style);
- // Keep comments aligned with #, otherwise indent comments normally. These
- // tests cannot use verifyFormat because messUp manipulates leading
- // whitespace.
- {
- const char *Expected = ""
- "void f() {\n"
- "#if 1\n"
- "// Preprocessor aligned.\n"
- "# define A 0\n"
- " // Code. Separated by blank line.\n"
- "\n"
- "# define B 0\n"
- " // Code. Not aligned with #\n"
- "# define C 0\n"
- "#endif";
- const char *ToFormat = ""
- "void f() {\n"
- "#if 1\n"
- "// Preprocessor aligned.\n"
- "# define A 0\n"
- "// Code. Separated by blank line.\n"
- "\n"
- "# define B 0\n"
- " // Code. Not aligned with #\n"
- "# define C 0\n"
- "#endif";
- verifyFormat(Expected, ToFormat, Style);
- verifyNoChange(Expected, Style);
- }
- // Keep block quotes aligned.
- {
- const char *Expected = ""
- "void f() {\n"
- "#if 1\n"
- "/* Preprocessor aligned. */\n"
- "# define A 0\n"
- " /* Code. Separated by blank line. */\n"
- "\n"
- "# define B 0\n"
- " /* Code. Not aligned with # */\n"
- "# define C 0\n"
- "#endif";
- const char *ToFormat = ""
- "void f() {\n"
- "#if 1\n"
- "/* Preprocessor aligned. */\n"
- "# define A 0\n"
- "/* Code. Separated by blank line. */\n"
- "\n"
- "# define B 0\n"
- " /* Code. Not aligned with # */\n"
- "# define C 0\n"
- "#endif";
- verifyFormat(Expected, ToFormat, Style);
- verifyNoChange(Expected, Style);
- }
- // Keep comments aligned with un-indented directives.
- {
- const char *Expected = ""
- "void f() {\n"
- "// Preprocessor aligned.\n"
- "#define A 0\n"
- " // Code. Separated by blank line.\n"
- "\n"
- "#define B 0\n"
- " // Code. Not aligned with #\n"
- "#define C 0\n";
- const char *ToFormat = ""
- "void f() {\n"
- "// Preprocessor aligned.\n"
- "#define A 0\n"
- "// Code. Separated by blank line.\n"
- "\n"
- "#define B 0\n"
- " // Code. Not aligned with #\n"
- "#define C 0\n";
- verifyFormat(Expected, ToFormat, Style);
- verifyNoChange(Expected, Style);
- }
- // Test AfterHash with tabs.
- {
- FormatStyle Tabbed = Style;
- Tabbed.UseTab = FormatStyle::UT_Always;
- Tabbed.IndentWidth = 8;
- Tabbed.TabWidth = 8;
- verifyFormat("#ifdef _WIN32\n"
- "#\tdefine A 0\n"
- "#\tifdef VAR2\n"
- "#\t\tdefine B 1\n"
- "#\t\tinclude <someheader.h>\n"
- "#\t\tdefine MACRO \\\n"
- "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
- "#\tendif\n"
- "#else\n"
- "#\tdefine A 1\n"
- "#endif",
- Tabbed);
- }
-
- // Regression test: Multiline-macro inside include guards.
- verifyFormat("#ifndef HEADER_H\n"
- "#define HEADER_H\n"
- "#define A() \\\n"
- " int i; \\\n"
- " int j;\n"
- "#endif // HEADER_H",
- getLLVMStyleWithColumns(20));
-
- Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
- // Basic before hash indent tests
- verifyFormat("#ifdef _WIN32\n"
- " #define A 0\n"
- " #ifdef VAR2\n"
- " #define B 1\n"
- " #include <someheader.h>\n"
- " #define MACRO \\\n"
- " some_very_long_func_aaaaaaaaaa();\n"
- " #endif\n"
- "#else\n"
- " #define A 1\n"
- "#endif",
- Style);
- verifyFormat("#if A\n"
- " #define MACRO \\\n"
- " void a(int x) { \\\n"
- " b(); \\\n"
- " c(); \\\n"
- " d(); \\\n"
- " e(); \\\n"
- " f(); \\\n"
- " }\n"
- "#endif",
- Style);
- // Keep comments aligned with indented directives. These
- // tests cannot use verifyFormat because messUp manipulates leading
- // whitespace.
- {
- const char *Expected = "void f() {\n"
- "// Aligned to preprocessor.\n"
- "#if 1\n"
- " // Aligned to code.\n"
- " int a;\n"
- " #if 1\n"
- " // Aligned to preprocessor.\n"
- " #define A 0\n"
- " // Aligned to code.\n"
- " int b;\n"
- " #endif\n"
- "#endif\n"
- "}";
- const char *ToFormat = "void f() {\n"
- "// Aligned to preprocessor.\n"
- "#if 1\n"
- "// Aligned to code.\n"
- "int a;\n"
- "#if 1\n"
- "// Aligned to preprocessor.\n"
- "#define A 0\n"
- "// Aligned to code.\n"
- "int b;\n"
- "#endif\n"
- "#endif\n"
- "}";
- verifyFormat(Expected, ToFormat, Style);
- verifyNoChange(Expected, Style);
- }
- {
- const char *Expected = "void f() {\n"
- "/* Aligned to preprocessor. */\n"
- "#if 1\n"
- " /* Aligned to code. */\n"
- " int a;\n"
- " #if 1\n"
- " /* Aligned to preprocessor. */\n"
- " #define A 0\n"
- " /* Aligned to code. */\n"
- " int b;\n"
- " #endif\n"
- "#endif\n"
- "}";
- const char *ToFormat = "void f() {\n"
- "/* Aligned to preprocessor. */\n"
- "#if 1\n"
- "/* Aligned to code. */\n"
- "int a;\n"
- "#if 1\n"
- "/* Aligned to preprocessor. */\n"
- "#define A 0\n"
- "/* Aligned to code. */\n"
- "int b;\n"
- "#endif\n"
- "#endif\n"
- "}";
- verifyFormat(Expected, ToFormat, Style);
- verifyNoChange(Expected, Style);
- }
-
- // Test single comment before preprocessor
- verifyFormat("// Comment\n"
- "\n"
- "#if 1\n"
- "#endif",
- Style);
-
- verifyFormat("#ifndef ABCDE\n"
- " #define ABCDE 0\n"
- "#endif\n"
- "\n"
- "#define FGHIJK",
- "#ifndef ABCDE\n"
- "#define ABCDE 0\n"
- "#endif\n"
- "\n"
- "#define FGHIJK",
- Style);
-
- verifyFormat("#ifndef FOO_H\n"
- "#define FOO_H\n"
- "#include <iostream>\n"
- "#endif\n"
- "// comment",
- Style);
-}
-
-TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
- verifyFormat("{\n"
- " {\n"
- " a #c;\n"
- " }\n"
- "}");
-}
-
-TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
- verifyFormat("#define A \\\n { \\\n {\nint i;",
- "#define A { {\nint i;", getLLVMStyleWithColumns(11));
- verifyFormat("#define A \\\n } \\\n }\nint i;",
- "#define A } }\nint i;", getLLVMStyleWithColumns(11));
-}
-
-TEST_F(FormatTest, EscapedNewlines) {
- FormatStyle Narrow = getLLVMStyleWithColumns(11);
- verifyFormat("#define A \\\n int i; \\\n int j;",
- "#define A \\\nint i;\\\n int j;", Narrow);
- verifyFormat("#define A\n\nint i;", "#define A \\\n\n int i;");
- verifyFormat("template <class T> f();", "\\\ntemplate <class T> f();");
- verifyFormat("/* \\ \\ \\\n */", "\\\n/* \\ \\ \\\n */");
- verifyNoChange("<a\n\\\\\n>");
-
- FormatStyle AlignLeft = getLLVMStyle();
- AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- verifyFormat("#define MACRO(x) \\\n"
- "private: \\\n"
- " int x(int a);",
- AlignLeft);
-
- // Escaped with a trigraph. The program just has to avoid crashing.
- verifyNoCrash("#define A \?\?/\n"
- "int i;\?\?/\n"
- " int j;");
- verifyNoCrash("#define A \?\?/\r\n"
- "int i;\?\?/\r\n"
- " int j;");
- verifyNoCrash("#define A \?\?/\n"
- "int i;",
- getGoogleStyle(FormatStyle::LK_CSharp));
-
- // CRLF line endings
- verifyFormat("#define A \\\r\n int i; \\\r\n int j;",
- "#define A \\\r\nint i;\\\r\n int j;", Narrow);
- verifyFormat("#define A\r\n\r\nint i;", "#define A \\\r\n\r\n int i;");
- verifyFormat("template <class T> f();", "\\\ntemplate <class T> f();");
- verifyFormat("/* \\ \\ \\\r\n */", "\\\r\n/* \\ \\ \\\r\n */");
- verifyNoChange("<a\r\n\\\\\r\n>");
- verifyFormat("#define MACRO(x) \\\r\n"
- "private: \\\r\n"
- " int x(int a);",
- AlignLeft);
-
- constexpr StringRef Code("#define A \\\n"
- " int a123; \\\n"
- " int a; \\\n"
- " int a1234;");
- verifyFormat(Code, AlignLeft);
-
- constexpr StringRef Code2("#define A \\\n"
- " int a123; \\\n"
- " int a; \\\n"
- " int a1234;");
- auto LastLine = getLLVMStyle();
- LastLine.AlignEscapedNewlines = FormatStyle::ENAS_LeftWithLastLine;
- verifyFormat(Code2, LastLine);
-
- LastLine.ColumnLimit = 13;
- verifyFormat(Code, LastLine);
-
- LastLine.ColumnLimit = 0;
- verifyFormat(Code2, LastLine);
-
- FormatStyle DontAlign = getLLVMStyle();
- DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
- DontAlign.MaxEmptyLinesToKeep = 3;
- // FIXME: can't use verifyFormat here because the newline before
- // "public:" is not inserted the first time it's reformatted
- verifyNoChange("#define A \\\n"
- " class Foo { \\\n"
- " void bar(); \\\n"
- "\\\n"
- "\\\n"
- "\\\n"
- " public: \\\n"
- " void baz(); \\\n"
- " };",
- DontAlign);
-}
-
-TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
- verifyFormat("#define A \\\n"
- " int v( \\\n"
- " a); \\\n"
- " int i;",
- getLLVMStyleWithColumns(11));
-}
-
-TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
- verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
- " \\\n"
- " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
- "\n"
- "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
- " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);",
- " #define ALooooooooooooooooooooooooooooooooooooooongMacro("
- "\\\n"
- "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
- " \n"
- " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
- " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);");
-}
-
-TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
- verifyFormat("int\n"
- "#define A\n"
- " a;",
- "int\n#define A\na;");
- verifyFormat("functionCallTo(\n"
- " someOtherFunction(\n"
- " withSomeParameters, whichInSequence,\n"
- " areLongerThanALine(andAnotherCall,\n"
- "#define A B\n"
- " withMoreParamters,\n"
- " whichStronglyInfluenceTheLayout),\n"
- " andMoreParameters),\n"
- " trailing);",
- getLLVMStyleWithColumns(69));
- verifyFormat("Foo::Foo()\n"
- "#ifdef BAR\n"
- " : baz(0)\n"
- "#endif\n"
- "{\n"
- "}");
- verifyFormat("void f() {\n"
- " if (true)\n"
- "#ifdef A\n"
- " f(42);\n"
- " x();\n"
- "#else\n"
- " g();\n"
- " x();\n"
- "#endif\n"
- "}");
- verifyFormat("void f(param1, param2,\n"
- " param3,\n"
- "#ifdef A\n"
- " param4(param5,\n"
- "#ifdef A1\n"
- " param6,\n"
- "#ifdef A2\n"
- " param7),\n"
- "#else\n"
- " param8),\n"
- " param9,\n"
- "#endif\n"
- " param10,\n"
- "#endif\n"
- " param11)\n"
- "#else\n"
- " param12)\n"
- "#endif\n"
- "{\n"
- " x();\n"
- "}",
- getLLVMStyleWithColumns(28));
- verifyFormat("#if 1\n"
- "int i;");
- verifyFormat("#if 1\n"
- "#endif\n"
- "#if 1\n"
- "#else\n"
- "#endif");
- verifyFormat("DEBUG({\n"
- " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
- "});\n"
- "#if a\n"
- "#else\n"
- "#endif");
-
- verifyIncompleteFormat("void f(\n"
- "#if A\n"
- ");\n"
- "#else\n"
- "#endif");
-
- // Verify that indentation is correct when there is an `#if 0` with an
- // `#else`.
- verifyFormat("#if 0\n"
- "{\n"
- "#else\n"
- "{\n"
- "#endif\n"
- " x;\n"
- "}");
-
- verifyFormat("#if 0\n"
- "#endif\n"
- "#if X\n"
- "int something_fairly_long; // Align here please\n"
- "#endif // Should be aligned");
-
- verifyFormat("#if 0\n"
- "#endif\n"
- "#if X\n"
- "#else // Align\n"
- ";\n"
- "#endif // Align");
-
- verifyFormat("void SomeFunction(int param1,\n"
- " template <\n"
- "#ifdef A\n"
- "#if 0\n"
- "#endif\n"
- " MyType<Some>>\n"
- "#else\n"
- " Type1, Type2>\n"
- "#endif\n"
- " param2,\n"
- " param3) {\n"
- " f();\n"
- "}");
-
- verifyFormat("#ifdef __cplusplus\n"
- "extern \"C\"\n"
- "#endif\n"
- " void f();");
-}
-
-TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
- verifyFormat("#endif\n"
- "#if B");
-}
-
-TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
- FormatStyle SingleLine = getLLVMStyle();
- SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
- verifyFormat("#if 0\n"
- "#elif 1\n"
- "#endif\n"
- "void foo() {\n"
- " if (test) foo2();\n"
- "}",
- SingleLine);
-}
-
-TEST_F(FormatTest, LayoutBlockInsideParens) {
- verifyFormat("functionCall({ int i; });");
- verifyFormat("functionCall({\n"
- " int i;\n"
- " int j;\n"
- "});");
- verifyFormat("functionCall(\n"
- " {\n"
- " int i;\n"
- " int j;\n"
- " },\n"
- " aaaa, bbbb, cccc);");
- verifyFormat("functionA(functionB({\n"
- " int i;\n"
- " int j;\n"
- " }),\n"
- " aaaa, bbbb, cccc);");
- verifyFormat("functionCall(\n"
- " {\n"
- " int i;\n"
- " int j;\n"
- " },\n"
- " aaaa, bbbb, // comment\n"
- " cccc);");
- verifyFormat("functionA(functionB({\n"
- " int i;\n"
- " int j;\n"
- " }),\n"
- " aaaa, bbbb, // comment\n"
- " cccc);");
- verifyFormat("functionCall(aaaa, bbbb, { int i; });");
- verifyFormat("functionCall(aaaa, bbbb, {\n"
- " int i;\n"
- " int j;\n"
- "});");
- verifyFormat(
- "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
- " {\n"
- " int i; // break\n"
- " },\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
- " ccccccccccccccccc));");
- verifyFormat("DEBUG({\n"
- " if (a)\n"
- " f();\n"
- "});");
-}
-
-TEST_F(FormatTest, LayoutBlockInsideStatement) {
- verifyFormat("SOME_MACRO { int i; }\n"
- "int i;",
- " SOME_MACRO {int i;} int i;");
-}
-
-TEST_F(FormatTest, LayoutNestedBlocks) {
- verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
- " struct s {\n"
- " int i;\n"
- " };\n"
- " s kBitsToOs[] = {{10}};\n"
- " for (int i = 0; i < 10; ++i)\n"
- " return;\n"
- "}");
- verifyFormat("call(parameter, {\n"
- " something();\n"
- " // Comment using all columns.\n"
- " somethingelse();\n"
- "});",
- getLLVMStyleWithColumns(40));
- verifyFormat("DEBUG( //\n"
- " { f(); }, a);");
- verifyFormat("DEBUG( //\n"
- " {\n"
- " f(); //\n"
- " },\n"
- " a);");
-
- verifyFormat("call(parameter, {\n"
- " something();\n"
- " // Comment too\n"
- " // looooooooooong.\n"
- " somethingElse();\n"
- "});",
- "call(parameter, {\n"
- " something();\n"
- " // Comment too looooooooooong.\n"
- " somethingElse();\n"
- "});",
- getLLVMStyleWithColumns(29));
- verifyFormat("DEBUG({ int i; });", "DEBUG({ int i; });");
- verifyFormat("DEBUG({ // comment\n"
- " int i;\n"
- "});",
- "DEBUG({ // comment\n"
- "int i;\n"
- "});");
- verifyFormat("DEBUG({\n"
- " int i;\n"
- "\n"
- " // comment\n"
- " int j;\n"
- "});",
- "DEBUG({\n"
- " int i;\n"
- "\n"
- " // comment\n"
- " int j;\n"
- "});");
-
- verifyFormat("DEBUG({\n"
- " if (a)\n"
- " return;\n"
- "});");
- verifyGoogleFormat("DEBUG({\n"
- " if (a) return;\n"
- "});");
- FormatStyle Style = getGoogleStyle();
- Style.ColumnLimit = 45;
- verifyFormat("Debug(\n"
- " aaaaa,\n"
- " {\n"
- " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
- " },\n"
- " a);",
- Style);
-
- verifyFormat("SomeFunction({MACRO({ return output; }), b});");
-
- verifyNoCrash("^{v^{a}}");
-}
-
-TEST_F(FormatTest, FormatNestedBlocksInMacros) {
- verifyFormat("#define MACRO() \\\n"
- " Debug(aaa, /* force line break */ \\\n"
- " { \\\n"
- " int i; \\\n"
- " int j; \\\n"
- " })",
- "#define MACRO() Debug(aaa, /* force line break */ \\\n"
- " { int i; int j; })",
- getGoogleStyle());
-
- verifyFormat("#define A \\\n"
- " [] { \\\n"
- " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
- " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
- " }",
- "#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
- getGoogleStyle());
-}
-
-TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
- verifyFormat("enum E {};");
- verifyFormat("enum E {}");
- FormatStyle Style = getLLVMStyle();
- Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
- verifyFormat("void f() { }", "void f() {}", Style);
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
- verifyFormat("{ }", Style);
- verifyFormat("while (true) { }", "while (true) {}", Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.BeforeElse = false;
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
- verifyFormat("if (a)\n"
- "{\n"
- "} else if (b)\n"
- "{\n"
- "} else\n"
- "{ }",
- Style);
- Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
- verifyFormat("if (a) {\n"
- "} else if (b) {\n"
- "} else {\n"
- "}",
- Style);
- Style.BraceWrapping.BeforeElse = true;
- verifyFormat("if (a) { }\n"
- "else if (b) { }\n"
- "else { }",
- Style);
-
- Style = getLLVMStyle(FormatStyle::LK_CSharp);
- Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
- verifyFormat("Event += () => { };", Style);
-}
-
-TEST_F(FormatTest, FormatBeginBlockEndMacros) {
- FormatStyle Style = getLLVMStyle();
- Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
- Style.MacroBlockEnd = "^[A-Z_]+_END$";
- verifyFormat("FOO_BEGIN\n"
- " FOO_ENTRY\n"
- "FOO_END",
- Style);
- verifyFormat("FOO_BEGIN\n"
- " NESTED_FOO_BEGIN\n"
- " NESTED_FOO_ENTRY\n"
- " NESTED_FOO_END\n"
- "FOO_END",
- Style);
- verifyFormat("FOO_BEGIN(Foo, Bar)\n"
- " int x;\n"
- " x = 1;\n"
- "FOO_END(Baz)",
- Style);
-
- Style.RemoveBracesLLVM = true;
- verifyNoCrash("for (;;)\n"
- " FOO_BEGIN\n"
- " foo();\n"
- " FOO_END",
- Style);
-}
-
-//===----------------------------------------------------------------------===//
-// Line break tests.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, PreventConfusingIndents) {
- verifyFormat(
- "void f() {\n"
- " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
- " parameter, parameter, parameter)),\n"
- " SecondLongCall(parameter));\n"
- "}");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaa]];");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa>;");
- verifyFormat("int a = bbbb && ccc &&\n"
- " fffff(\n"
- "#define A Just forcing a new line\n"
- " ddd);");
-}
-
-TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
- verifyFormat(
- "bool aaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
- " bbbbbbbb();");
- verifyFormat(
- "bool aaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
- " bbbbbbbb();");
-
- verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
- " ccccccccc == ddddddddddd;");
- verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
- " ccccccccc == ddddddddddd;");
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
- " ccccccccc == ddddddddddd;");
-
- verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
- " aaaaaa) &&\n"
- " bbbbbb && cccccc;");
- verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
- " aaaaaa) >>\n"
- " bbbbbb;");
- verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
- " SourceMgr.getSpellingColumnNumber(\n"
- " TheLine.Last->FormatTok.Tok.getLocation()) -\n"
- " 1);");
-
- verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
- " cccccc) {\n}");
- verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
- " cccccc) {\n}");
- verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
- " cccccc) {\n}");
- verifyFormat("b = a &&\n"
- " // Comment\n"
- " b.c && d;");
-
- // If the LHS of a comparison is not a binary expression itself, the
- // additional linebreak confuses many people.
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
- "}");
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
- "}");
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
- "}");
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
- "}");
- // Even explicit parentheses stress the precedence enough to make the
- // additional break unnecessary.
- verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
- "}");
- // This cases is borderline, but with the indentation it is still readable.
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
- "}",
- getLLVMStyleWithColumns(75));
-
- // If the LHS is a binary expression, we should still use the additional break
- // as otherwise the formatting hides the operator precedence.
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
- " 5) {\n"
- "}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
- " 5) {\n"
- "}");
-
- FormatStyle OnePerLine = getLLVMStyle();
- OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
- OnePerLine);
-
- verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
- " .aaa(aaaaaaaaaaaaa) *\n"
- " aaaaaaa +\n"
- " aaaaaaa;",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, ExpressionIndentation) {
- verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
- " ccccccccccccccccccccccccccccccccccccccccc;");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
- verifyFormat("if () {\n"
- "} else if (aaaaa && bbbbb > // break\n"
- " ccccc) {\n"
- "}");
- verifyFormat("if () {\n"
- "} else if constexpr (aaaaa && bbbbb > // break\n"
- " ccccc) {\n"
- "}");
- verifyFormat("if () {\n"
- "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
- " ccccc) {\n"
- "}");
- verifyFormat("if () {\n"
- "} else if (aaaaa &&\n"
- " bbbbb > // break\n"
- " ccccc &&\n"
- " ddddd) {\n"
- "}");
-
- // Presence of a trailing comment used to change indentation of b.
- verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
- " b;\n"
- "return aaaaaaaaaaaaaaaaaaa +\n"
- " b; //",
- getLLVMStyleWithColumns(30));
-}
-
-TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
- // Not sure what the best system is here. Like this, the LHS can be found
- // immediately above an operator (everything with the same or a higher
- // indent). The RHS is aligned right of the operator and so compasses
- // everything until something with the same indent as the operator is found.
- // FIXME: Is this a good system?
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat(
- "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " > ccccccccccccccccccccccccccccccccccccccccc;",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if () {\n"
- "} else if (aaaaa\n"
- " && bbbbb // break\n"
- " > ccccc) {\n"
- "}",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
- Style);
- verifyFormat("return (a)\n"
- " // comment\n"
- " + b;",
- Style);
- verifyFormat(
- "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + cc;",
- Style);
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
-
- // Forced by comments.
- verifyFormat(
- "unsigned ContentSize =\n"
- " sizeof(int16_t) // DWARF ARange version number\n"
- " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
- " + sizeof(int8_t) // Pointer Size (in bytes)\n"
- " + sizeof(int8_t); // Segment Size (in bytes)");
-
- verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
- " == boost::fusion::at_c<1>(iiii).second;",
- Style);
-
- Style.ColumnLimit = 60;
- verifyFormat("zzzzzzzzzz\n"
- " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
-
- Style.ColumnLimit = 80;
- Style.IndentWidth = 4;
- Style.TabWidth = 4;
- Style.UseTab = FormatStyle::UT_Always;
- Style.AlignAfterOpenBracket = false;
- Style.AlignOperands = FormatStyle::OAS_DontAlign;
- verifyFormat("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
- "\t&& (someOtherLongishConditionPart1\n"
- "\t\t|| someOtherEvenLongerNestedConditionPart2);",
- "return someVeryVeryLongConditionThatBarelyFitsOnALine && "
- "(someOtherLongishConditionPart1 || "
- "someOtherEvenLongerNestedConditionPart2);",
- Style);
-
- Style = getLLVMStyleWithColumns(20);
- Style.BreakAfterOpenBracketFunction = true;
- Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- Style.ContinuationIndentWidth = 2;
- verifyFormat("struct Foo {\n"
- " Foo(\n"
- " int arg1,\n"
- " int arg2)\n"
- " : Base(\n"
- " arg1,\n"
- " arg2) {}\n"
- "};",
- Style);
- verifyFormat("return abc\n"
- " ? foo(\n"
- " a,\n"
- " b,\n"
- " bar(\n"
- " abc))\n"
- " : g(abc);",
- Style);
-}
-
-TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
-
- verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " > ccccccccccccccccccccccccccccccccccccccccc;",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
- Style);
- verifyFormat("if () {\n"
- "} else if (aaaaa\n"
- " && bbbbb // break\n"
- " > ccccc) {\n"
- "}",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
- Style);
- verifyFormat("return (a)\n"
- " // comment\n"
- " + b;",
- Style);
- verifyFormat(
- "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + cc;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : ccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee)\n"
- " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
-
- verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
- " == boost::fusion::at_c<1>(iiii).second;",
- Style);
-
- Style.ColumnLimit = 60;
- verifyFormat("zzzzzzzzzzzzz\n"
- " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
-
- // Forced by comments.
- Style.ColumnLimit = 80;
- verifyFormat(
- "unsigned ContentSize\n"
- " = sizeof(int16_t) // DWARF ARange version number\n"
- " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
- " + sizeof(int8_t) // Pointer Size (in bytes)\n"
- " + sizeof(int8_t); // Segment Size (in bytes)",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- verifyFormat(
- "unsigned ContentSize =\n"
- " sizeof(int16_t) // DWARF ARange version number\n"
- " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
- " + sizeof(int8_t) // Pointer Size (in bytes)\n"
- " + sizeof(int8_t); // Segment Size (in bytes)",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
- verifyFormat(
- "unsigned ContentSize =\n"
- " sizeof(int16_t) // DWARF ARange version number\n"
- " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
- " + sizeof(int8_t) // Pointer Size (in bytes)\n"
- " + sizeof(int8_t); // Segment Size (in bytes)",
- Style);
-}
-
-TEST_F(FormatTest, EnforcedOperatorWraps) {
- // Here we'd like to wrap after the || operators, but a comment is forcing an
- // earlier wrap.
- verifyFormat("bool x = aaaaa //\n"
- " || bbbbb\n"
- " //\n"
- " || cccc;");
-}
-
-TEST_F(FormatTest, NoOperandAlignment) {
- FormatStyle Style = getLLVMStyle();
- Style.AlignOperands = FormatStyle::OAS_DontAlign;
- verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " > ccccccccccccccccccccccccccccccccccccccccc;",
- Style);
-
- verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " + cc;",
- Style);
- verifyFormat("int a = aa\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
- " * cccccccccccccccccccccccccccccccccccc;",
- Style);
-
- Style.AlignAfterOpenBracket = false;
- verifyFormat("return (a > b\n"
- " // comment1\n"
- " // comment2\n"
- " || c);",
- Style);
-}
-
-TEST_F(FormatTest, BreakingBeforeNonAssignmentOperators) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
- Style);
-}
-
-TEST_F(FormatTest, AllowBinPackingInsideArguments) {
- FormatStyle Style = getLLVMStyleWithColumns(40);
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- Style.BinPackArguments = false;
- verifyFormat("void test() {\n"
- " someFunction(\n"
- " this + argument + is + quite\n"
- " + long + so + it + gets + wrapped\n"
- " + but + remains + bin - packed);\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " someFunction(arg1,\n"
- " this + argument + is\n"
- " + quite + long + so\n"
- " + it + gets + wrapped\n"
- " + but + remains + bin\n"
- " - packed,\n"
- " arg3);\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " someFunction(\n"
- " arg1,\n"
- " this + argument + has\n"
- " + anotherFunc(nested,\n"
- " calls + whose\n"
- " + arguments\n"
- " + are + also\n"
- " + wrapped,\n"
- " in + addition)\n"
- " + to + being + bin - packed,\n"
- " arg3);\n"
- "}",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
- verifyFormat("void test() {\n"
- " someFunction(\n"
- " arg1,\n"
- " this + argument + has +\n"
- " anotherFunc(nested,\n"
- " calls + whose +\n"
- " arguments +\n"
- " are + also +\n"
- " wrapped,\n"
- " in + addition) +\n"
- " to + being + bin - packed,\n"
- " arg3);\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
- auto Style = getLLVMStyleWithColumns(45);
- EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
- verifyFormat("bool b =\n"
- " is_default_constructible_v<hash<T>> and\n"
- " is_copy_constructible_v<hash<T>> and\n"
- " is_move_constructible_v<hash<T>> and\n"
- " is_copy_assignable_v<hash<T>> and\n"
- " is_move_assignable_v<hash<T>> and\n"
- " is_destructible_v<hash<T>> and\n"
- " is_swappable_v<hash<T>> and\n"
- " is_callable_v<hash<T>(T)>;",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
- verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
- " and is_copy_constructible_v<hash<T>>\n"
- " and is_move_constructible_v<hash<T>>\n"
- " and is_copy_assignable_v<hash<T>>\n"
- " and is_move_assignable_v<hash<T>>\n"
- " and is_destructible_v<hash<T>>\n"
- " and is_swappable_v<hash<T>>\n"
- " and is_callable_v<hash<T>(T)>;",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
- " and is_copy_constructible_v<hash<T>>\n"
- " and is_move_constructible_v<hash<T>>\n"
- " and is_copy_assignable_v<hash<T>>\n"
- " and is_move_assignable_v<hash<T>>\n"
- " and is_destructible_v<hash<T>>\n"
- " and is_swappable_v<hash<T>>\n"
- " and is_callable_v<hash<T>(T)>;",
- Style);
-}
-
-TEST_F(FormatTest, ConstructorInitializers) {
- verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
- verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
- getLLVMStyleWithColumns(45));
- verifyFormat("Constructor()\n"
- " : Inttializer(FitsOnTheLine) {}",
- getLLVMStyleWithColumns(44));
- verifyFormat("Constructor()\n"
- " : Inttializer(FitsOnTheLine) {}",
- getLLVMStyleWithColumns(43));
-
- verifyFormat("template <typename T>\n"
- "Constructor() : Initializer(FitsOnTheLine) {}",
- getLLVMStyleWithColumns(45));
-
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
-
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
- verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " : aaaaaaaaaa(aaaaaa) {}");
-
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaa() {}");
-
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
-
- verifyFormat("Constructor(int Parameter = 0)\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
- "}",
- getLLVMStyleWithColumns(60));
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
-
- // Here a line could be saved by splitting the second initializer onto two
- // lines, but that is not desirable.
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaa(aaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
-
- FormatStyle OnePerLine = getLLVMStyle();
- OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
- verifyFormat("MyClass::MyClass()\n"
- " : a(a),\n"
- " b(b),\n"
- " c(c) {}",
- OnePerLine);
- verifyFormat("MyClass::MyClass()\n"
- " : a(a), // comment\n"
- " b(b),\n"
- " c(c) {}",
- OnePerLine);
- verifyFormat("MyClass::MyClass(int a)\n"
- " : b(a), // comment\n"
- " c(a + 1) { // lined up\n"
- "}",
- OnePerLine);
- verifyFormat("Constructor()\n"
- " : a(b, b, b) {}",
- OnePerLine);
- OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- OnePerLine);
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- OnePerLine);
- verifyFormat("MyClass::MyClass(int var)\n"
- " : some_var_(var), // 4 space indent\n"
- " some_other_var_(var + 1) { // lined up\n"
- "}",
- OnePerLine);
- verifyFormat("Constructor()\n"
- " : aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa) {}",
- OnePerLine);
- verifyFormat("Constructor()\n"
- " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaa) {}",
- OnePerLine);
- OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat(
- "Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaa().aaa(),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- OnePerLine);
- OnePerLine.ColumnLimit = 60;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
- OnePerLine);
-
- verifyFormat("Constructor()\n"
- " : // Comment forcing unwanted break.\n"
- " aaaa(aaaa) {}",
- "Constructor() :\n"
- " // Comment forcing unwanted break.\n"
- " aaaa(aaaa) {}");
-
- // Braced initializers with trailing commas.
- verifyFormat("MyClass::MyClass()\n"
- " : aaaa{\n"
- " 0,\n"
- " },\n"
- " bbbb{\n"
- " 0,\n"
- " } {}",
- "MyClass::MyClass():aaaa{0,},bbbb{0,}{}");
-}
-
-TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
- FormatStyle Style = getLLVMStyleWithColumns(60);
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
-
- for (int i = 0; i < 4; ++i) {
- // Test all combinations of parameters that should not have an effect.
- Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
- Style.AllowAllArgumentsOnNextLine = i & 2;
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
- verifyFormat("Constructor() : a(a), b(b) {}", Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a)\n"
- " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
- verifyFormat("Constructor() : a(a), b(b) {}", Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
- verifyFormat("Constructor()\n"
- " : a(a), b(b) {}",
- Style);
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a)\n"
- " , bbbbbbbbbbbbbbbbbbbbb(b)\n"
- " , cccccccccccccccccccccc(c) {}",
- Style);
-
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
- verifyFormat("Constructor()\n"
- " : a(a), b(b) {}",
- Style);
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b),\n"
- " cccccccccccccccccccccc(c) {}",
- Style);
-
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
- verifyFormat("Constructor() :\n"
- " a(a), b(b) {}",
- Style);
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b),\n"
- " cccccccccccccccccccccc(c) {}",
- Style);
- }
-
- // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
- // AllowAllConstructorInitializersOnNextLine in all
- // BreakConstructorInitializers modes
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- Style.AllowAllParametersOfDeclarationOnNextLine = true;
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a)\n"
- " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.AllowAllParametersOfDeclarationOnNextLine = false;
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a)\n"
- " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
-
- Style.AllowAllParametersOfDeclarationOnNextLine = true;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.AllowAllParametersOfDeclarationOnNextLine = false;
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb)\n"
- " : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
- Style.AllowAllParametersOfDeclarationOnNextLine = true;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
- " aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc) :\n"
- " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb,\n"
- " int cccccccccccccccc) :\n"
- " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.AllowAllParametersOfDeclarationOnNextLine = false;
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb) :\n"
- " aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style = getLLVMStyleWithColumns(0);
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("Foo(Bar bar, Baz baz) : bar(bar), baz(baz) {}", Style);
- verifyNoChange("Foo(Bar bar, Baz baz)\n"
- " : bar(bar), baz(baz) {}",
- Style);
-}
-
-TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
- FormatStyle Style = getLLVMStyleWithColumns(60);
- Style.BinPackArguments = false;
- for (int i = 0; i < 4; ++i) {
- // Test all combinations of parameters that should not have an effect.
- Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
- Style.PackConstructorInitializers =
- i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
-
- Style.AllowAllArgumentsOnNextLine = true;
- verifyFormat("void foo() {\n"
- " FunctionCallWithReallyLongName(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
- "}",
- Style);
- Style.AllowAllArgumentsOnNextLine = false;
- verifyFormat("void foo() {\n"
- " FunctionCallWithReallyLongName(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbb);\n"
- "}",
- Style);
-
- Style.AllowAllArgumentsOnNextLine = true;
- verifyFormat("void foo() {\n"
- " auto VariableWithReallyLongName = {\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
- "}",
- Style);
- Style.AllowAllArgumentsOnNextLine = false;
- verifyFormat("void foo() {\n"
- " auto VariableWithReallyLongName = {\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbb};\n"
- "}",
- Style);
- }
-
- // This parameter should not affect declarations.
- Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- Style.AllowAllArgumentsOnNextLine = false;
- Style.AllowAllParametersOfDeclarationOnNextLine = true;
- verifyFormat("void FunctionCallWithReallyLongName(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
- Style);
- Style.AllowAllParametersOfDeclarationOnNextLine = false;
- verifyFormat("void FunctionCallWithReallyLongName(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbb);",
- Style);
-}
-
-TEST_F(FormatTest, BreakFunctionDefinitionParameters) {
- StringRef Input = "void functionDecl(paramA, paramB, paramC);\n"
- "void emptyFunctionDefinition() {}\n"
- "void functionDefinition(int A, int B, int C) {}\n"
- "Class::Class(int A, int B) : m_A(A), m_B(B) {}";
- verifyFormat(Input);
-
- FormatStyle Style = getLLVMStyle();
- EXPECT_FALSE(Style.BreakFunctionDefinitionParameters);
- Style.BreakFunctionDefinitionParameters = true;
- verifyFormat("void functionDecl(paramA, paramB, paramC);\n"
- "void emptyFunctionDefinition() {}\n"
- "void functionDefinition(\n"
- " int A, int B, int C) {}\n"
- "Class::Class(\n"
- " int A, int B)\n"
- " : m_A(A), m_B(B) {}",
- Input, Style);
-
- // Test the style where all parameters are on their own lines.
- Style.AllowAllParametersOfDeclarationOnNextLine = false;
- Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("void functionDecl(paramA, paramB, paramC);\n"
- "void emptyFunctionDefinition() {}\n"
- "void functionDefinition(\n"
- " int A,\n"
- " int B,\n"
- " int C) {}\n"
- "Class::Class(\n"
- " int A,\n"
- " int B)\n"
- " : m_A(A), m_B(B) {}",
- Input, Style);
-}
-
-TEST_F(FormatTest, BreakBeforeInlineASMColon) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Never;
- /* Test the behaviour with long lines */
- Style.ColumnLimit = 40;
- verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
- " : : val);",
- Style);
- verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
- " : val1 : val2);",
- Style);
- verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
- " \"cpuid\\n\\t\"\n"
- " \"xchgq\\t%%rbx %%rsi\\n\\t\",\n"
- " : \"=a\" : \"a\");",
- Style);
- Style.ColumnLimit = 80;
- verifyFormat("asm volatile(\"string\", : : val);", Style);
- verifyFormat("asm volatile(\"string\", : val1 : val2);", Style);
-
- Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Always;
- verifyFormat("asm volatile(\"string\",\n"
- " :\n"
- " : val);",
- Style);
- verifyFormat("asm volatile(\"string\",\n"
- " : val1\n"
- " : val2);",
- Style);
- /* Test the behaviour with long lines */
- Style.ColumnLimit = 40;
- verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
- " \"cpuid\\n\\t\"\n"
- " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
- " : \"=a\"(*rEAX)\n"
- " : \"a\"(value));",
- Style);
- verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
- " \"cpuid\\n\\t\"\n"
- " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
- " :\n"
- " : \"a\"(value));",
- Style);
- verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
- " :\n"
- " : val);",
- Style);
- verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
- " : val1\n"
- " : val2);",
- Style);
-}
-
-TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
-
- verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
- verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
- getStyleWithColumns(Style, 45));
- verifyFormat("Constructor() :\n"
- " Initializer(FitsOnTheLine) {}",
- getStyleWithColumns(Style, 44));
- verifyFormat("Constructor() :\n"
- " Initializer(FitsOnTheLine) {}",
- getStyleWithColumns(Style, 43));
-
- verifyFormat("template <typename T>\n"
- "Constructor() : Initializer(FitsOnTheLine) {}",
- getStyleWithColumns(Style, 50));
- verifyFormat(
- "Class::Class(int some, int arguments, int loooooooooooooooooooong,\n"
- " int mooooooooooooore) noexcept :\n"
- " Super{some, arguments}, Member{5}, Member2{2} {}",
- Style);
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat(
- "SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
- verifyFormat(
- "SomeClass::Constructor() : // NOLINT\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat(
- "SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
- verifyFormat(
- "SomeClass::Constructor() : // NOLINT\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
- verifyFormat(
- "SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- verifyFormat(
- "SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
- verifyFormat(
- "SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
- verifyFormat(
- "Ctor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) : aaaaaaaaaa(aaaaaa) {}",
- Style);
-
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaa() {}",
- Style);
-
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- Style);
-
- verifyFormat("Constructor(int Parameter = 0) :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
- Style);
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
- "}",
- getStyleWithColumns(Style, 60));
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
- Style);
-
- // Here a line could be saved by splitting the second initializer onto two
- // lines, but that is not desirable.
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaa(aaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- Style);
-
- FormatStyle OnePerLine = Style;
- OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- OnePerLine);
- verifyFormat("SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- OnePerLine);
- verifyFormat("Foo::Foo(int i, int j) : // NOLINT\n"
- " i(i), // comment\n"
- " j(j) {}",
- OnePerLine);
- verifyFormat("MyClass::MyClass(int var) :\n"
- " some_var_(var), // 4 space indent\n"
- " some_other_var_(var + 1) { // lined up\n"
- "}",
- OnePerLine);
- verifyFormat("Constructor() :\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa),\n"
- " aaaaa(aaaaaa) {}",
- OnePerLine);
- verifyFormat("Constructor() :\n"
- " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaa) {}",
- OnePerLine);
- OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaa().aaa(),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- OnePerLine);
- OnePerLine.ColumnLimit = 60;
- verifyFormat("Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
- OnePerLine);
-
- verifyFormat("Constructor() :\n"
- " // Comment forcing unwanted break.\n"
- " aaaa(aaaa) {}",
- Style);
- verifyFormat("Constructor() : // NOLINT\n"
- " aaaa(aaaa) {}",
- Style);
- verifyFormat("Constructor() : // A very long trailing comment that cannot fit"
- " on a single\n"
- " // line.\n"
- " aaaa(aaaa) {}",
- "Constructor() : // A very long trailing comment that cannot fit"
- " on a single line.\n"
- " aaaa(aaaa) {}",
- Style);
-
- Style.ColumnLimit = 0;
- verifyNoChange("SomeClass::Constructor() :\n"
- " a(a) {}",
- Style);
- verifyNoChange("SomeClass::Constructor() noexcept :\n"
- " a(a) {}",
- Style);
- verifyNoChange("SomeClass::Constructor() :\n"
- " a(a), b(b), c(c) {}",
- Style);
- verifyNoChange("SomeClass::Constructor() :\n"
- " a(a) {\n"
- " foo();\n"
- " bar();\n"
- "}",
- Style);
- verifyFormat("struct Foo {\n"
- " int x;\n"
- " Foo() : x(0) {}\n"
- "};",
- "struct Foo {\n"
- " int x;\n"
- " Foo():x(0) {}\n"
- "};",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- verifyNoChange("SomeClass::Constructor() :\n"
- " a(a), b(b), c(c) {\n"
- "}",
- Style);
- verifyNoChange("SomeClass::Constructor() :\n"
- " a(a) {\n"
- "}",
- Style);
-
- Style.ColumnLimit = 80;
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- Style.ConstructorInitializerIndentWidth = 2;
- verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
- verifyFormat("SomeClass::Constructor() :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
- Style);
-
- // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
- // well
- Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
- verifyFormat(
- "class SomeClass\n"
- " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
- Style);
- Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
- verifyFormat(
- "class SomeClass\n"
- " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
- Style);
- Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
- verifyFormat(
- "class SomeClass :\n"
- " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
- Style);
- Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
- verifyFormat(
- "class SomeClass\n"
- " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
- Style);
-}
-
-TEST_F(FormatTest, BreakConstructorInitializersAfterComma) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterComma;
-
- verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", Style);
- verifyFormat("Constructor() : a(a), b(b), c(c) {}", Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
- verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
- verifyFormat("SomeClassWithALongName::Constructor(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb) : aaaaaaaaaaaaaaaaaaaa(a),\n"
- " bbbbbbbbbbbbbbbbbbbbb(b) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
- verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
- Style);
-
- Style.ColumnLimit = 0;
- Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
- verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
- verifyNoChange("SomeClass::Constructor() : a(a),\n"
- " b(b),\n"
- " c(c) {}",
- Style);
-}
-
-#ifndef EXPENSIVE_CHECKS
-// Expensive checks enables libstdc++ checking which includes validating the
-// state of ranges used in std::priority_queue - this blows out the
-// runtime/scalability of the function and makes this test unacceptably slow.
-TEST_F(FormatTest, MemoizationTests) {
- // This breaks if the memoization lookup does not take \c Indent and
- // \c LastSpace into account.
- verifyFormat(
- "extern CFRunLoopTimerRef\n"
- "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
- " CFTimeInterval interval, CFOptionFlags flags,\n"
- " CFIndex order, CFRunLoopTimerCallBack callout,\n"
- " CFRunLoopTimerContext *context) {}");
-
- // Deep nesting somewhat works around our memoization.
- verifyFormat(
- "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
- " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
- " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
- " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
- " aaaaa())))))))))))))))))))))))))))))))))))))));",
- getLLVMStyleWithColumns(65));
- verifyFormat(
- "aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa(\n"
- " aaaaa,\n"
- " aaaaa))))))))))));",
- getLLVMStyleWithColumns(65));
- verifyFormat(
- "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a),\n"
- " a)",
- getLLVMStyleWithColumns(65));
-
- // This test takes VERY long when memoization is broken.
- FormatStyle OnePerLine = getLLVMStyle();
- OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- std::string input = "Constructor()\n"
- " : aaaa(a,\n";
- for (unsigned i = 0, e = 80; i != e; ++i)
- input += " a,\n";
- input += " a) {}";
- verifyFormat(input, OnePerLine);
- OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat(input, OnePerLine);
-}
-#endif
-
-TEST_F(FormatTest, BreaksAsHighAsPossible) {
- verifyFormat(
- "void f() {\n"
- " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
- " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
- " f();\n"
- "}");
- verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
- " Intervals[i - 1].getRange().getLast()) {\n}");
-}
-
-TEST_F(FormatTest, BreaksFunctionDeclarations) {
- // Principially, we break function declarations in a certain order:
- // 1) break amongst arguments.
- verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
- " Cccccccccccccc cccccccccccccc);");
- verifyFormat("template <class TemplateIt>\n"
- "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
- " TemplateIt *stop) {}");
-
- // 2) break after return type.
- verifyGoogleFormat(
- "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);");
-
- // 3) break after (.
- verifyGoogleFormat(
- "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
- " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);");
-
- // 4) break before after nested name specifiers.
- verifyGoogleFormat(
- "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);");
-
- // However, there are exceptions, if a sufficient amount of lines can be
- // saved.
- // FIXME: The precise cut-offs wrt. the number of saved lines might need some
- // more adjusting.
- verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc);");
- verifyGoogleFormat(
- "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
- verifyFormat(
- "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc);");
- verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
- " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
-
- // Break after multi-line parameters.
- verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbb bbbb);");
- verifyFormat("void SomeLoooooooooooongFunction(\n"
- " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbb);");
-
- // Treat overloaded operators like other functions.
- verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
- "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
- verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
- "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
- verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
- "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
- verifyGoogleFormat(
- "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
- " const SomeLooooooooogType& a, const SomeLooooooooogType& b);");
- verifyGoogleFormat(
- "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
- " const SomeLooooooooogType& a, const SomeLooooooooogType& b);");
-
- verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
- "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
- verifyGoogleFormat(
- "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
- "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " bool* aaaaaaaaaaaaaaaaaa, bool* aa) {}");
- verifyGoogleFormat("template <typename T>\n"
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
-
- verifyFormat("extern \"C\" //\n"
- " void f();");
-
- auto Style = getLLVMStyle();
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
- Style);
- verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- Style);
-
- Style = getLLVMStyleWithColumns(45);
- Style.PenaltyReturnTypeOnItsOwnLine = 400;
- verifyFormat("template <bool abool, // a comment\n"
- " bool anotherbool>\n"
- "static inline std::pair<size_t, MyCustomType>\n"
- "myfunc(const char *buf, const char *&err);",
- Style);
-}
-
-TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
- // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
- // Prefer keeping `::` followed by `operator` together.
- verifyFormat("const aaaa::bbbbbbb &\n"
- "ccccccccc::operator++() {\n"
- " stuff();\n"
- "}",
- "const aaaa::bbbbbbb\n"
- "&ccccccccc::operator++() { stuff(); }",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, TrailingReturnType) {
- verifyFormat("auto foo() -> int;");
- // correct trailing return type spacing
- verifyFormat("auto operator->() -> int;");
- verifyFormat("auto operator++(int) -> int;");
-
- verifyFormat("struct S {\n"
- " auto bar() const -> int;\n"
- "};");
- verifyFormat("template <size_t Order, typename T>\n"
- "auto load_img(const std::string &filename)\n"
- " -> alias::tensor<Order, T, mem::tag::cpu> {}");
- verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
- " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
- verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
- verifyFormat("template <typename T>\n"
- "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
- " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
-
- FormatStyle Style = getLLVMStyleWithColumns(60);
- verifyFormat("#define MAKE_DEF(NAME) \\\n"
- " auto NAME() -> int { return 42; }",
- Style);
-
- // Not trailing return types.
- verifyFormat("void f() { auto a = b->c(); }");
- verifyFormat("auto a = p->foo();");
- verifyFormat("int a = p->foo();");
- verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
-}
-
-TEST_F(FormatTest, DeductionGuides) {
- verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
- verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
- verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
- verifyFormat(
- "template <class... T>\n"
- "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
- verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
- verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
- verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
- verifyFormat("template <class T> A() -> A<(3 < 2)>;");
- verifyFormat("template <class T> A() -> A<((3) < (2))>;");
- verifyFormat("template <class T> x() -> x<1>;");
- verifyFormat("template <class T> explicit x(T &) -> x<1>;");
-
- verifyFormat("A(const char *) -> A<string &>;");
- verifyFormat("A() -> A<int>;");
-
- // Ensure not deduction guides.
- verifyFormat("c()->f<int>();");
- verifyFormat("x()->foo<1>;");
- verifyFormat("x = p->foo<3>();");
- verifyFormat("x()->x<1>();");
-}
-
-TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
- // Avoid breaking before trailing 'const' or other trailing annotations, if
- // they are not function-like.
- FormatStyle Style = getGoogleStyleWithColumns(47);
- verifyFormat("void someLongFunction(\n"
- " int someLoooooooooooooongParameter) const {\n}",
- getLLVMStyleWithColumns(47));
- verifyFormat("LoooooongReturnType\n"
- "someLoooooooongFunction() const {}",
- getLLVMStyleWithColumns(47));
- verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
- " const {}",
- Style);
- verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
- verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
- verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
- verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
- " aaaaaaaaaaa aaaaa) const override;");
- verifyGoogleFormat(
- "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " const override;");
-
- // Even if the first parameter has to be wrapped.
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) const {}",
- getLLVMStyleWithColumns(46));
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) const {}",
- Style);
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) override {}",
- Style);
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) OVERRIDE {}",
- Style);
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) final {}",
- Style);
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) FINAL {}",
- Style);
- verifyFormat("void someLongFunction(\n"
- " int parameter) const override {}",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) const\n"
- "{\n"
- "}",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
- verifyFormat("void someLongFunction(\n"
- " int someLongParameter) const\n"
- " {\n"
- " }",
- Style);
-
- // Unless these are unknown annotations.
- verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " LONG_AND_UGLY_ANNOTATION;");
-
- // Breaking before function-like trailing annotations is fine to keep them
- // close to their arguments.
- verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
- verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
- " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
- verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
- " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
- verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
- " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
- verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
-
- verifyFormat(
- "void aaaaaaaaaaaaaaaaaa()\n"
- " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa));");
- verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " __attribute__((unused));");
-
- Style = getGoogleStyle();
-
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " GUARDED_BY(aaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " GUARDED_BY(aaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
- " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
-
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ABSL_GUARDED_BY(aaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ABSL_GUARDED_BY(aaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ABSL_GUARDED_BY(aaaaaaaaaaaa) =\n"
- " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ABSL_GUARDED_BY(aaaaaaaaaaaa) =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
-}
-
-TEST_F(FormatTest, FunctionAnnotations) {
- verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
- "int OldFunction(const string ¶meter) {}");
- verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
- "string OldFunction(const string ¶meter) {}");
- verifyFormat("template <typename T>\n"
- "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
- "string OldFunction(const string ¶meter) {}");
-
- // Not function annotations.
- verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
- verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
- " ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
- verifyFormat("MACRO(abc).function() // wrap\n"
- " << abc;");
- verifyFormat("MACRO(abc)->function() // wrap\n"
- " << abc;");
- verifyFormat("MACRO(abc)::function() // wrap\n"
- " << abc;");
- verifyFormat("FOO(bar)();", getLLVMStyleWithColumns(0));
-}
-
-TEST_F(FormatTest, BreaksDesireably) {
- verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
- " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
- " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
- "}");
-
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
-
- verifyFormat(
- "aaaaaaaa(aaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
- " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat(
- "void f() {\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
- "}");
- verifyFormat(
- "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
- verifyFormat(
- "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
- verifyFormat(
- "aaaaaa(aaa,\n"
- " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaa);");
- verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- // Indent consistently independent of call expression and unary operator.
- verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
- " dddddddddddddddddddddddddddddd));");
- verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
- " dddddddddddddddddddddddddddddd));");
- verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
- " dddddddddddddddddddddddddddddd));");
-
- // This test case breaks on an incorrect memoization, i.e. an optimization not
- // taking into account the StopAt value.
- verifyFormat(
- "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("{\n {\n {\n"
- " Annotation.SpaceRequiredBefore =\n"
- " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
- " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
- " }\n }\n}");
-
- // Break on an outer level if there was a break on an inner level.
- verifyFormat("f(g(h(a, // comment\n"
- " b, c),\n"
- " d, e),\n"
- " x, y);",
- "f(g(h(a, // comment\n"
- " b, c), d, e), x, y);");
-
- // Prefer breaking similar line breaks.
- verifyFormat(
- "const int kTrackingOptions = NSTrackingMouseMoved |\n"
- " NSTrackingMouseEnteredAndExited |\n"
- " NSTrackingActiveAlways;");
-}
-
-TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
- FormatStyle NoBinPacking = getGoogleStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- NoBinPacking.BinPackArguments = true;
- verifyFormat("void f() {\n"
- " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
- "}",
- NoBinPacking);
- verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
- " int aaaaaaaaaaaaaaaaaaaa,\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
- NoBinPacking);
-
- NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
- verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " vector<int> bbbbbbbbbbbbbbb);",
- NoBinPacking);
- // FIXME: This behavior difference is probably not wanted. However, currently
- // we cannot distinguish BreakBeforeParameter being set because of the wrapped
- // template arguments from BreakBeforeParameter being set because of the
- // one-per-line formatting.
- verifyFormat(
- "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaa> aaaaaaaaaa);",
- NoBinPacking);
- verifyFormat(
- "void fffffffffff(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
- " aaaaaaaaaa);");
-}
-
-TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
- FormatStyle NoBinPacking = getGoogleStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- NoBinPacking.BinPackArguments = false;
- verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
- NoBinPacking);
- verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
- NoBinPacking);
- verifyFormat(
- "aaaaaaaa(aaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
- " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
- NoBinPacking);
- verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaaaaa();",
- NoBinPacking);
- verifyFormat("void f() {\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
- "}",
- NoBinPacking);
-
- verifyFormat(
- "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaa,\n"
- " aaaaaaaaaaaa);",
- NoBinPacking);
- verifyFormat(
- "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
- " ddddddddddddddddddddddddddddd),\n"
- " test);",
- NoBinPacking);
-
- verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaa>\n"
- " aaaaaaaaaaaaaaaaaa;",
- NoBinPacking);
- verifyFormat("a(\"a\"\n"
- " \"a\",\n"
- " a);");
-
- NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
- verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
- " aaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- NoBinPacking);
- verifyFormat(
- "void f() {\n"
- " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaa();\n"
- "}",
- NoBinPacking);
- verifyFormat(
- "template <class SomeType, class SomeOtherType>\n"
- "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
- NoBinPacking);
-}
-
-TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
- FormatStyle Style = getLLVMStyleWithColumns(15);
- Style.ExperimentalAutoDetectBinPacking = true;
- verifyFormat("aaa(aaaa,\n"
- " aaaa,\n"
- " aaaa);\n"
- "aaa(aaaa,\n"
- " aaaa,\n"
- " aaaa);",
- "aaa(aaaa,\n" // one-per-line
- " aaaa,\n"
- " aaaa );\n"
- "aaa(aaaa, aaaa, aaaa);", // inconclusive
- Style);
- verifyFormat("aaa(aaaa, aaaa,\n"
- " aaaa);\n"
- "aaa(aaaa, aaaa,\n"
- " aaaa);",
- "aaa(aaaa, aaaa,\n" // bin-packed
- " aaaa );\n"
- "aaa(aaaa, aaaa, aaaa);", // inconclusive
- Style);
-}
-
-TEST_F(FormatTest, IndentExportBlock) {
- FormatStyle Style = getLLVMStyleWithColumns(80);
- Style.IndentExportBlock = true;
- verifyFormat("export {\n"
- " int x;\n"
- " int y;\n"
- "}",
- "export {\n"
- "int x;\n"
- "int y;\n"
- "}",
- Style);
-
- Style.IndentExportBlock = false;
- verifyFormat("export {\n"
- "int x;\n"
- "int y;\n"
- "}",
- "export {\n"
- " int x;\n"
- " int y;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, ShortExportBlocks) {
- FormatStyle Style = getLLVMStyleWithColumns(80);
- Style.IndentExportBlock = false;
-
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
- verifyFormat("export {\n"
- "}",
- Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- "export\n"
- "{\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export {\n"
- "}",
- "export {}", Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- "export { int x; }", Style);
-
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- verifyFormat("export {}",
- "export {\n"
- "}",
- Style);
-
- verifyFormat("export { int x; }",
- "export {\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export { int x; }",
- "export\n"
- "{\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export {}",
- "export {\n"
- "}",
- Style);
-
- verifyFormat("export { int x; }",
- "export {\n"
- "int x;\n"
- "}",
- Style);
-
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
- verifyFormat("export {}",
- "export {\n"
- "}",
- Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- "export\n"
- "{\n"
- "int x;\n"
- "}",
- Style);
-
- verifyFormat("export {}", Style);
-
- verifyFormat("export {\n"
- "int x;\n"
- "}",
- "export { int x; }", Style);
-}
-
-TEST_F(FormatTest, FormatsBuilderPattern) {
- verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
- " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
- " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
- " .StartsWith(\".init\", ORDER_INIT)\n"
- " .StartsWith(\".fini\", ORDER_FINI)\n"
- " .StartsWith(\".hash\", ORDER_HASH)\n"
- " .Default(ORDER_TEXT);");
-
- verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
- " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
- verifyFormat("aaaaaaa->aaaaaaa\n"
- " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaa->aaaaaaa\n"
- " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
- " aaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
- " aaaaaa->aaaaaaaaaaaa()\n"
- " ->aaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " ->aaaaaaaaaaaaaaaaa();");
- verifyGoogleFormat(
- "void f() {\n"
- " someo->Add((new util::filetools::Handler(dir))\n"
- " ->OnEvent1(NewPermanentCallback(\n"
- " this, &HandlerHolderClass::EventHandlerCBA))\n"
- " ->OnEvent2(NewPermanentCallback(\n"
- " this, &HandlerHolderClass::EventHandlerCBB))\n"
- " ->OnEvent3(NewPermanentCallback(\n"
- " this, &HandlerHolderClass::EventHandlerCBC))\n"
- " ->OnEvent5(NewPermanentCallback(\n"
- " this, &HandlerHolderClass::EventHandlerCBD))\n"
- " ->OnEvent6(NewPermanentCallback(\n"
- " this, &HandlerHolderClass::EventHandlerCBE)));\n"
- "}");
-
- verifyFormat(
- "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
- verifyFormat("aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa();");
- verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa();");
- verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaa();");
- verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " ->aaaaaaaaaaaaaae(0)\n"
- " ->aaaaaaaaaaaaaaa();");
-
- // Don't linewrap after very short segments.
- verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("aaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " .has<bbbbbbbbbbbbbbbbbbbbb>();");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
-
- // Prefer not to break after empty parentheses.
- verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
- " First->LastNewlineOffset);");
-
- // Prefer not to create "hanging" indents.
- verifyFormat(
- "return !soooooooooooooome_map\n"
- " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .second;");
- verifyFormat(
- "return aaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
- " .aaaa(aaaaaaaaaaaaaa);");
- // No hanging indent here.
- verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
- " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- getLLVMStyleWithColumns(60));
- verifyFormat("aaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
- " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- getLLVMStyleWithColumns(59));
- verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- // Dont break if only closing statements before member call
- verifyFormat("test() {\n"
- " ([]() -> {\n"
- " int b = 32;\n"
- " return 3;\n"
- " }).foo();\n"
- "}");
- verifyFormat("test() {\n"
- " (\n"
- " []() -> {\n"
- " int b = 32;\n"
- " return 3;\n"
- " },\n"
- " foo, bar)\n"
- " .foo();\n"
- "}");
- verifyFormat("test() {\n"
- " ([]() -> {\n"
- " int b = 32;\n"
- " return 3;\n"
- " })\n"
- " .foo()\n"
- " .bar();\n"
- "}");
- verifyFormat("test() {\n"
- " ([]() -> {\n"
- " int b = 32;\n"
- " return 3;\n"
- " })\n"
- " .foo(\"aaaaaaaaaaaaaaaaa\"\n"
- " \"bbbb\");\n"
- "}",
- getLLVMStyleWithColumns(30));
-}
-
-TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
-
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
- " ccccccccccccccccccccccccc) {\n}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
- " ccccccccccccccccccccccccc) {\n}");
-
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
- " ccccccccccccccccccccccccc) {\n}");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
- " ccccccccccccccccccccccccc) {\n}");
-
- verifyFormat(
- "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
- " ccccccccccccccccccccccccc) {\n}");
- verifyFormat(
- "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
- " ccccccccccccccccccccccccc) {\n}");
-
- verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
- " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
- " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
- " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
- verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
- " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
- " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
- " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
-
- verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
- " aaaaaaaaaaaaaaa != aa) {\n}");
- verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
- " aaaaaaaaaaaaaaa != aa) {\n}");
-}
-
-TEST_F(FormatTest, BreaksAfterAssignments) {
- verifyFormat(
- "unsigned Cost =\n"
- " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
- " SI->getPointerAddressSpaceee());");
- verifyFormat(
- "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
- " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
-
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("unsigned OriginalStartColumn =\n"
- " SourceMgr.getSpellingColumnNumber(\n"
- " Current.FormatTok.getStartOfNonWhitespace()) -\n"
- " 1;");
-}
-
-TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
- Style);
-
- Style.PenaltyBreakAssignment = 20;
- verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
- " cccccccccccccccccccccccccc;",
- Style);
-}
-
-TEST_F(FormatTest, AlignsAfterAssignments) {
- verifyFormat(
- "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa;");
-}
-
-TEST_F(FormatTest, AlignsAfterReturn) {
- verifyFormat(
- "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
- " aaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat(
- "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
- " aaaaaaaaaaaaaaaaaaaaaa());");
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("return\n"
- " // true if code is one of a or b.\n"
- " code == a || code == b;");
-}
-
-TEST_F(FormatTest, BreaksConditionalExpressions) {
- verifyFormat(
- "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
- " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
- " : aaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa);");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa);");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaa;");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaa;");
- verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
- " aaaaaaaaa\n"
- " ? b\n"
- " : c);");
- verifyFormat("return aaaa == bbbb\n"
- " // comment\n"
- " ? aaaa\n"
- " : bbbb;");
- verifyFormat("unsigned Indent =\n"
- " format(TheLine.First,\n"
- " IndentForLevel[TheLine.Level] >= 0\n"
- " ? IndentForLevel[TheLine.Level]\n"
- " : TheLine * 2,\n"
- " TheLine.InPPDirective, PreviousEndOfLineColumn);",
- getLLVMStyleWithColumns(60));
- verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
- " ? aaaaaaaaaaaaaaa\n"
- " : bbbbbbbbbbbbbbb //\n"
- " ? ccccccccccccccc\n"
- " : ddddddddddddddd;");
- verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
- " ? aaaaaaaaaaaaaaa\n"
- " : (bbbbbbbbbbbbbbb //\n"
- " ? ccccccccccccccc\n"
- " : ddddddddddddddd);");
- verifyFormat(
- "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaa +\n"
- " aaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaa;");
- verifyFormat(
- "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
-
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackArguments = false;
- verifyFormat(
- "void f() {\n"
- " g(aaa,\n"
- " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaa\n"
- " : aaaaaaaaaaaaaaa);\n"
- "}",
- NoBinPacking);
- verifyFormat(
- "void f() {\n"
- " g(aaa,\n"
- " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ?: aaaaaaaaaaaaaaa);\n"
- "}",
- NoBinPacking);
-
- verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
- " // comment.\n"
- " ccccccccccccccccccccccccccccccccccccccc\n"
- " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
-
- // Assignments in conditional expressions. Apparently not uncommon :-(.
- verifyFormat("return a != b\n"
- " // comment\n"
- " ? a = b\n"
- " : a = b;");
- verifyFormat("return a != b\n"
- " // comment\n"
- " ? a = a != b\n"
- " // comment\n"
- " ? a = b\n"
- " : a\n"
- " : a;");
- verifyFormat("return a != b\n"
- " // comment\n"
- " ? a\n"
- " : a = a != b\n"
- " // comment\n"
- " ? a = b\n"
- " : a;");
-
- // Chained conditionals
- FormatStyle Style = getLLVMStyleWithColumns(70);
- Style.AlignOperands = FormatStyle::OAS_Align;
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 222222\n"
- " : 333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : cccccccccccccc ? 3333333333333333\n"
- " : 4444444444444444;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : (aaa ? bbb : ccc);",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccccc)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccccc)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : dddddddddddddddddd)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : dddddddddddddddddd)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : dddddddddddddddddd)",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccccc);",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : ccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : ccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee)\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccccc\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee\n"
- " : bbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
- " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee)\n"
- " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
- " : cccccccccccccccc ? dddddddddddddddddd\n"
- " : eeeeeeeeeeeeeeeeee\n"
- " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
- " : 3333333333333333;",
- Style);
-
- Style.AlignOperands = FormatStyle::OAS_DontAlign;
- Style.BreakBeforeTernaryOperators = false;
- // FIXME: Aligning the question marks is weird given DontAlign.
- // Consider disabling this alignment in this case. Also check whether this
- // will render the adjustment from https://reviews.llvm.org/D82199
- // unnecessary.
- verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
- " bbbb ? cccccccccccccccccc :\n"
- " ddddd;",
- Style);
-
- verifyFormat(
- "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
- " /*\n"
- " */\n"
- " function() {\n"
- " try {\n"
- " return JJJJJJJJJJJJJJ(\n"
- " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
- " }\n"
- " } :\n"
- " function() {};",
- "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
- " /*\n"
- " */\n"
- " function() {\n"
- " try {\n"
- " return JJJJJJJJJJJJJJ(\n"
- " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
- " }\n"
- " } :\n"
- " function() {};",
- getGoogleStyle(FormatStyle::LK_JavaScript));
-}
-
-TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
- FormatStyle Style = getLLVMStyleWithColumns(70);
- Style.BreakBeforeTernaryOperators = false;
- verifyFormat(
- "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
- " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
- " aaaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa);",
- Style);
- verifyFormat(
- "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaa);",
- Style);
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- Style);
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaa :\n"
- " aaaaaaaaaaaaaaa;",
- Style);
- verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
- " aaaaaaaaa ?\n"
- " b :\n"
- " c);",
- Style);
- verifyFormat("unsigned Indent =\n"
- " format(TheLine.First,\n"
- " IndentForLevel[TheLine.Level] >= 0 ?\n"
- " IndentForLevel[TheLine.Level] :\n"
- " TheLine * 2,\n"
- " TheLine.InPPDirective, PreviousEndOfLineColumn);",
- Style);
- verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
- " aaaaaaaaaaaaaaa :\n"
- " bbbbbbbbbbbbbbb ? //\n"
- " ccccccccccccccc :\n"
- " ddddddddddddddd;",
- Style);
- verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
- " aaaaaaaaaaaaaaa :\n"
- " (bbbbbbbbbbbbbbb ? //\n"
- " ccccccccccccccc :\n"
- " ddddddddddddddd);",
- Style);
- verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
- " ccccccccccccccccccccccccccc;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaa :\n"
- " bbbbbbbbbbbbbbb + cccccccccccccccc;",
- Style);
-
- // Chained conditionals
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 222222 :\n"
- " 333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " cccccccccccccccc ? 3333333333333333 :\n"
- " 4444444444444444;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " (aaa ? bbb : ccc);",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " dddddddddddddddddd) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " dddddddddddddddddd) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " dddddddddddddddddd)",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc);",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " ccccccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " ccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " ccccccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee) :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat(
- "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee :\n"
- " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
- " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee) :\n"
- " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
- " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
- " cccccccccccccccccccc ? dddddddddddddddddd :\n"
- " eeeeeeeeeeeeeeeeee :\n"
- " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
- " 3333333333333333;",
- Style);
-}
-
-TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
- verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
- " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
- verifyFormat("bool a = true, b = false;");
-
- verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
- verifyFormat(
- "bool aaaaaaaaaaaaaaaaaaaaa =\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
- " d = e && f;");
- verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
- " c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
- verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
- " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
- verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
- " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
-
- FormatStyle Style = getGoogleStyle();
- Style.PointerAlignment = FormatStyle::PAS_Left;
- Style.DerivePointerAlignment = false;
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
- " *b = bbbbbbbbbbbbbbbbbbb;",
- Style);
- verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
- " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
- Style);
- verifyFormat("vector<int*> a, b;", Style);
- verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
- verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
- verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style);
- verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}",
- Style);
- verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}",
- Style);
- verifyFormat(
- "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}",
- Style);
-
- verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
- verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
- verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
- verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
- verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}",
- Style);
-}
-
-TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
- verifyFormat("arr[foo ? bar : baz];");
- verifyFormat("f()[foo ? bar : baz];");
- verifyFormat("(a + b)[foo ? bar : baz];");
- verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
-}
-
-TEST_F(FormatTest, AlignsStringLiterals) {
- verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
- " \"short literal\");");
- verifyFormat(
- "looooooooooooooooooooooooongFunction(\n"
- " \"short literal\"\n"
- " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
- verifyFormat("someFunction(\"Always break between multi-line\"\n"
- " \" string literals\",\n"
- " also, other, parameters);");
- verifyFormat("fun + \"1243\" /* comment */\n"
- " \"5678\";",
- "fun + \"1243\" /* comment */\n"
- " \"5678\";",
- getLLVMStyleWithColumns(28));
- verifyFormat(
- "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
- " \"aaaaaaaaaaaaaaaaaaaaa\"\n"
- " \"aaaaaaaaaaaaaaaa\";",
- "aaaaaa ="
- "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaa\" "
- "\"aaaaaaaaaaaaaaaa\";");
- verifyFormat("a = a + \"a\"\n"
- " \"a\"\n"
- " \"a\";");
- verifyFormat("f(\"a\", \"b\"\n"
- " \"c\");");
-
- verifyFormat(
- "#define LL_FORMAT \"ll\"\n"
- "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
- " \"d, ddddddddd: %\" LL_FORMAT \"d\");");
-
- verifyFormat("#define A(X) \\\n"
- " \"aaaaa\" #X \"bbbbbb\" \\\n"
- " \"ccccc\"",
- getLLVMStyleWithColumns(23));
- verifyFormat("#define A \"def\"\n"
- "f(\"abc\" A \"ghi\"\n"
- " \"jkl\");");
-
- verifyFormat("f(L\"a\"\n"
- " L\"b\");");
- verifyFormat("#define A(X) \\\n"
- " L\"aaaaa\" #X L\"bbbbbb\" \\\n"
- " L\"ccccc\"",
- getLLVMStyleWithColumns(25));
-
- verifyFormat("f(@\"a\"\n"
- " @\"b\");");
- verifyFormat("NSString s = @\"a\"\n"
- " @\"b\"\n"
- " @\"c\";");
- verifyFormat("NSString s = @\"a\"\n"
- " \"b\"\n"
- " \"c\";");
-}
-
-TEST_F(FormatTest, ReturnTypeBreakingStyle) {
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 60;
-
- // No declarations or definitions should be moved to own line.
- Style.BreakAfterReturnType = FormatStyle::RTBS_None;
- verifyFormat("class A {\n"
- " int f() { return 1; }\n"
- " int g();\n"
- " long\n"
- " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
- "};\n"
- "int f() { return 1; }\n"
- "int g();\n"
- "int foooooooooooooooooooooooooooo::\n"
- " baaaaaaaaaaaaaaaaaaaaar();",
- Style);
-
- // It is now allowed to break after a short return type if necessary.
- Style.BreakAfterReturnType = FormatStyle::RTBS_Automatic;
- verifyFormat("class A {\n"
- " int f() { return 1; }\n"
- " int g();\n"
- " long\n"
- " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
- "};\n"
- "int f() { return 1; }\n"
- "int g();\n"
- "int\n"
- "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
- Style);
-
- // It now must never break after a short return type.
- Style.BreakAfterReturnType = FormatStyle::RTBS_ExceptShortType;
- verifyFormat("class A {\n"
- " int f() { return 1; }\n"
- " int g();\n"
- " long foooooooooooooooooooooooooooo::\n"
- " baaaaaaaaaaaaaaaaaaaar();\n"
- "};\n"
- "int f() { return 1; }\n"
- "int g();\n"
- "int foooooooooooooooooooooooooooo::\n"
- " baaaaaaaaaaaaaaaaaaaaar();",
- Style);
-
- // All declarations and definitions should have the return type moved to its
- // own line.
- Style.BreakAfterReturnType = FormatStyle::RTBS_All;
- Style.TypenameMacros = {"LIST"};
- verifyFormat("SomeType\n"
- "funcdecl(LIST(uint64_t));",
- Style);
- verifyFormat("class E {\n"
- " int\n"
- " f() {\n"
- " return 1;\n"
- " }\n"
- " int\n"
- " g();\n"
- " long\n"
- " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
- "};\n"
- "int\n"
- "f() {\n"
- " return 1;\n"
- "}\n"
- "int\n"
- "g();\n"
- "int\n"
- "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
- Style);
-
- // Top-level definitions, and no kinds of declarations should have the
- // return type moved to its own line.
- Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
- verifyFormat("class B {\n"
- " int f() { return 1; }\n"
- " int g();\n"
- "};\n"
- "int\n"
- "f() {\n"
- " return 1;\n"
- "}\n"
- "int g();",
- Style);
-
- // Top-level definitions and declarations should have the return type moved
- // to its own line.
- Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
- verifyFormat("class C {\n"
- " int f() { return 1; }\n"
- " int g();\n"
- "};\n"
- "int\n"
- "f() {\n"
- " return 1;\n"
- "}\n"
- "int\n"
- "g();\n"
- "int\n"
- "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
- Style);
-
- // All definitions should have the return type moved to its own line, but no
- // kinds of declarations.
- Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
- verifyFormat("class D {\n"
- " int\n"
- " f() {\n"
- " return 1;\n"
- " }\n"
- " int g();\n"
- "};\n"
- "int\n"
- "f() {\n"
- " return 1;\n"
- "}\n"
- "int g();",
- Style);
- verifyFormat("const char *\n"
- "f(void) {\n" // Break here.
- " return \"\";\n"
- "}\n"
- "const char *bar(void);", // No break here.
- Style);
- verifyFormat("template <class T>\n"
- "T *\n"
- "f(T &c) {\n" // Break here.
- " return NULL;\n"
- "}\n"
- "template <class T> T *f(T &c);", // No break here.
- Style);
- verifyFormat("class C {\n"
- " int\n"
- " operator+() {\n"
- " return 1;\n"
- " }\n"
- " int\n"
- " operator()() {\n"
- " return 1;\n"
- " }\n"
- "};",
- Style);
- verifyFormat("void\n"
- "A::operator()() {}\n"
- "void\n"
- "A::operator>>() {}\n"
- "void\n"
- "A::operator+() {}\n"
- "void\n"
- "A::operator*() {}\n"
- "void\n"
- "A::operator->() {}\n"
- "void\n"
- "A::operator&() {}\n"
- "void\n"
- "A::operator&&() {}\n"
- "void\n"
- "A::operator[]() {}\n"
- "void\n"
- "A::operator!() {}\n"
- "void\n"
- "A::operator<Foo> *() {}\n"
- "void\n"
- "A::operator<Foo> &() {}\n",
- Style);
- verifyFormat("constexpr auto\n"
- "operator()() const -> reference {}\n"
- "constexpr auto\n"
- "operator>>() const -> reference {}\n"
- "constexpr auto\n"
- "operator+() const -> reference {}\n"
- "constexpr auto\n"
- "operator*() const -> reference {}\n"
- "constexpr auto\n"
- "operator->() const -> reference {}\n"
- "constexpr auto\n"
- "operator++() const -> reference {}\n"
- "constexpr auto\n"
- "operator void *() const -> reference {}\n"
- "constexpr auto\n"
- "operator void **() const -> reference {}\n"
- "constexpr auto\n"
- "operator void *() const -> reference {}\n"
- "constexpr auto\n"
- "operator void &() const -> reference {}\n"
- "constexpr auto\n"
- "operator&&() const -> reference {}\n"
- "constexpr auto\n"
- "operator char *() const -> reference {}\n"
- "constexpr auto\n"
- "operator!() const -> reference {}\n"
- "constexpr auto\n"
- "operator[]() const -> reference {}",
- Style);
- verifyFormat("void *operator new(std::size_t s);", // No break here.
- Style);
- verifyFormat("void *\n"
- "operator new(std::size_t s) {}",
- Style);
- verifyFormat("void *\n"
- "operator delete[](void *ptr) {}",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
- verifyFormat("const char *\n"
- "f(void)\n" // Break here.
- "{\n"
- " return \"\";\n"
- "}\n"
- "const char *bar(void);", // No break here.
- Style);
- verifyFormat("template <class T>\n"
- "T *\n" // Problem here: no line break
- "f(T &c)\n" // Break here.
- "{\n"
- " return NULL;\n"
- "}\n"
- "template <class T> T *f(T &c);", // No break here.
- Style);
- verifyFormat("int\n"
- "foo(A<bool> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("int\n"
- "foo(A<8> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("int\n"
- "foo(A<B<bool>, 8> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("int\n"
- "foo(A<B<8>, bool> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("int\n"
- "foo(A<B<bool>, bool> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("int\n"
- "foo(A<B<8>, 8> a)\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- verifyFormat("int f(i);\n" // No break here.
- "int\n" // Break here.
- "f(i)\n"
- "{\n"
- " return i + 1;\n"
- "}\n"
- "int\n" // Break here.
- "f(i)\n"
- "{\n"
- " return i + 1;\n"
- "};",
- Style);
- verifyFormat("int f(a, b, c);\n" // No break here.
- "int\n" // Break here.
- "f(a, b, c)\n" // Break here.
- "short a, b;\n"
- "float c;\n"
- "{\n"
- " return a + b < c;\n"
- "}\n"
- "int\n" // Break here.
- "f(a, b, c)\n" // Break here.
- "short a, b;\n"
- "float c;\n"
- "{\n"
- " return a + b < c;\n"
- "};",
- Style);
- verifyFormat("byte *\n" // Break here.
- "f(a)\n" // Break here.
- "byte a[];\n"
- "{\n"
- " return a;\n"
- "}",
- Style);
- verifyFormat("byte *\n"
- "f(a)\n"
- "byte /* K&R C */ a[];\n"
- "{\n"
- " return a;\n"
- "}\n"
- "byte *\n"
- "g(p)\n"
- "byte /* K&R C */ *p;\n"
- "{\n"
- " return p;\n"
- "}",
- Style);
- verifyFormat("bool f(int a, int) override;\n"
- "Bar g(int a, Bar) final;\n"
- "Bar h(a, Bar) final;",
- Style);
- verifyFormat("int\n"
- "f(a)",
- Style);
- verifyFormat("bool\n"
- "f(size_t = 0, bool b = false)\n"
- "{\n"
- " return !b;\n"
- "}",
- Style);
-
- // The return breaking style doesn't affect:
- // * function and object definitions with attribute-like macros
- verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
- " ABSL_GUARDED_BY(mutex) = {};",
- getGoogleStyleWithColumns(40));
- verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
- " ABSL_GUARDED_BY(mutex); // comment",
- getGoogleStyleWithColumns(40));
- verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
- " ABSL_GUARDED_BY(mutex1)\n"
- " ABSL_GUARDED_BY(mutex2);",
- getGoogleStyleWithColumns(40));
- verifyFormat("Tttttt f(int a, int b)\n"
- " ABSL_GUARDED_BY(mutex1)\n"
- " ABSL_GUARDED_BY(mutex2);",
- getGoogleStyleWithColumns(40));
- // * typedefs
- verifyGoogleFormat("typedef ATTR(X) char x;");
-
- Style = getGNUStyle();
-
- // Test for comments at the end of function declarations.
- verifyFormat("void\n"
- "foo (int a, /*abc*/ int b) // def\n"
- "{\n"
- "}",
- Style);
-
- verifyFormat("void\n"
- "foo (int a, /* abc */ int b) /* def */\n"
- "{\n"
- "}",
- Style);
-
- // Definitions that should not break after return type
- verifyFormat("void foo (int a, int b); // def", Style);
- verifyFormat("void foo (int a, int b); /* def */", Style);
- verifyFormat("void foo (int a, int b);", Style);
-}
-
-TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
- FormatStyle NoBreak = getLLVMStyle();
- NoBreak.AlwaysBreakBeforeMultilineStrings = false;
- FormatStyle Break = getLLVMStyle();
- Break.AlwaysBreakBeforeMultilineStrings = true;
- verifyFormat("aaaa = \"bbbb\"\n"
- " \"cccc\";",
- NoBreak);
- verifyFormat("aaaa =\n"
- " \"bbbb\"\n"
- " \"cccc\";",
- Break);
- verifyFormat("aaaa(\"bbbb\"\n"
- " \"cccc\");",
- NoBreak);
- verifyFormat("aaaa(\n"
- " \"bbbb\"\n"
- " \"cccc\");",
- Break);
- verifyFormat("aaaa(qqq, \"bbbb\"\n"
- " \"cccc\");",
- NoBreak);
- verifyFormat("aaaa(qqq,\n"
- " \"bbbb\"\n"
- " \"cccc\");",
- Break);
- verifyFormat("aaaa(qqq,\n"
- " L\"bbbb\"\n"
- " L\"cccc\");",
- Break);
- verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
- " \"bbbb\"));",
- Break);
- verifyFormat("string s = someFunction(\n"
- " \"abc\"\n"
- " \"abc\");",
- Break);
-
- // As we break before unary operators, breaking right after them is bad.
- verifyFormat("string foo = abc ? \"x\"\n"
- " \"blah blah blah blah blah blah\"\n"
- " : \"y\";",
- Break);
-
- // Don't break if there is no column gain.
- verifyFormat("f(\"aaaa\"\n"
- " \"bbbb\");",
- Break);
-
- // Treat literals with escaped newlines like multi-line string literals.
- verifyNoChange("x = \"a\\\n"
- "b\\\n"
- "c\";",
- NoBreak);
- verifyFormat("xxxx =\n"
- " \"a\\\n"
- "b\\\n"
- "c\";",
- "xxxx = \"a\\\n"
- "b\\\n"
- "c\";",
- Break);
-
- verifyFormat("NSString *const kString =\n"
- " @\"aaaa\"\n"
- " @\"bbbb\";",
- "NSString *const kString = @\"aaaa\"\n"
- "@\"bbbb\";",
- Break);
-
- Break.ColumnLimit = 0;
- verifyFormat("const char *hello = \"hello llvm\";", Break);
-}
-
-TEST_F(FormatTest, AlignsPipes) {
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
- " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
- " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
- verifyFormat(
- "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
- verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
- verifyFormat(
- "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
- verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaa)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("LOG_IF(aaa == //\n"
- " bbb)\n"
- " << a << b;");
-
- // But sometimes, breaking before the first "<<" is desirable.
- verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
- verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
- " << BEF << IsTemplate << Description << E->getType();");
- verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " << aaa;");
-
- verifyFormat(
- "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
-
- // Incomplete string literal.
- verifyFormat("llvm::errs() << \"\n"
- " << a;",
- "llvm::errs() << \"\n<<a;");
-
- verifyFormat("void f() {\n"
- " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
- " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
- "}");
-
- // Handle 'endl'.
- verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
- " << bbbbbbbbbbbbbbbbbbbbbb << endl;");
- verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
-
- // Handle '\n'.
- verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
- " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
- verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
- " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
- verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
- " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
- verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
-}
-
-TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
- verifyFormat("return out << \"somepacket = {\\n\"\n"
- " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
- " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
- " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
- " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
- " << \"}\";");
-
- verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
- verifyFormat(
- "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
- " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
- " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
- " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
- " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
- verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
- " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
- verifyFormat(
- "void f() {\n"
- " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
- "}");
-
- // Breaking before the first "<<" is generally not desirable.
- verifyFormat(
- "llvm::errs()\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- getLLVMStyleWithColumns(70));
- verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
- " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
- getLLVMStyleWithColumns(70));
-
- verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
- " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
- " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
- verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
- " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
- " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
- verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
- " (aaaa + aaaa);",
- getLLVMStyleWithColumns(40));
- verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
- " (aaaaaaa + aaaaa));",
- getLLVMStyleWithColumns(40));
- verifyFormat(
- "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
- " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
- " bbbbbbbbbbbbbbbbbbbbbbb);");
-}
-
-TEST_F(FormatTest, WrapBeforeInsertionOperatorbetweenStringLiterals) {
- verifyFormat("QStringList() << \"foo\" << \"bar\";");
-
- verifyNoChange("QStringList() << \"foo\"\n"
- " << \"bar\";");
-
- verifyFormat("log_error(log, \"foo\" << \"bar\");",
- "log_error(log, \"foo\"\n"
- " << \"bar\");");
-}
-
-TEST_F(FormatTest, UnderstandsEquals) {
- verifyFormat(
- "aaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat(
- "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
- verifyFormat(
- "if (a) {\n"
- " f();\n"
- "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
- "}");
-
- verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " 100000000 + 10000000) {\n}");
-}
-
-TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
- verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
- " .looooooooooooooooooooooooooooooooooooooongFunction();");
-
- verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
- " ->looooooooooooooooooooooooooooooooooooooongFunction();");
-
- verifyFormat(
- "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
- " Parameter2);");
-
- verifyFormat(
- "ShortObject->shortFunction(\n"
- " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
- " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
-
- verifyFormat("loooooooooooooongFunction(\n"
- " LoooooooooooooongObject->looooooooooooooooongFunction());");
-
- verifyFormat(
- "function(LoooooooooooooooooooooooooooooooooooongObject\n"
- " ->loooooooooooooooooooooooooooooooooooooooongFunction());");
-
- verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
- " .WillRepeatedly(Return(SomeValue));");
- verifyFormat("void f() {\n"
- " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
- " .Times(2)\n"
- " .WillRepeatedly(Return(SomeValue));\n"
- "}");
- verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
- " ccccccccccccccccccccccc);");
- verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaa(aaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("void f() {\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
- "}");
- verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
- "}");
-
- // Here, it is not necessary to wrap at "." or "->".
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
- " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
- verifyFormat(
- "aaaaaaaaaaa->aaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));");
-
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
- verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
- " aaaaaaaaa()->aaaaaa()->aaaaa());");
- verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
- " aaaaaaaaa()->aaaaaa()->aaaaa());");
-
- verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .a();");
-
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- NoBinPacking);
-
- // If there is a subsequent call, change to hanging indentation.
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
- verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
-}
-
-TEST_F(FormatTest, WrapsTemplateDeclarations) {
- verifyFormat("template <typename T>\n"
- "virtual void loooooooooooongFunction(int Param1, int Param2);");
- verifyFormat("template <typename T>\n"
- "// T should be one of {A, B}.\n"
- "virtual void loooooooooooongFunction(int Param1, int Param2);");
- verifyFormat(
- "template <typename T>\n"
- "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
- verifyFormat("template <typename T>\n"
- "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
- " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
- verifyFormat(
- "template <typename T>\n"
- "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
- " int Paaaaaaaaaaaaaaaaaaaaram2);");
- verifyFormat(
- "template <typename T>\n"
- "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("template <typename T>\n"
- "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " int aaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat(
- "template <typename T1, typename T2 = char, typename T3 = char,\n"
- " typename T4 = char>\n"
- "void f();");
- verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
- " template <typename> class cccccccccccccccccccccc,\n"
- " typename ddddddddddddd>\n"
- "class C {};");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("void f() {\n"
- " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
- " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
- "}");
-
- verifyFormat("template <typename T> class C {};");
- verifyFormat("template <typename T> void f();");
- verifyFormat("template <typename T> void f() {}");
- verifyFormat(
- "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
- " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
- " bbbbbbbbbbbbbbbbbbbbbbbb);",
- getLLVMStyleWithColumns(72));
- verifyFormat("static_cast<A< //\n"
- " B> *>(\n"
- "\n"
- ");",
- "static_cast<A<//\n"
- " B>*>(\n"
- "\n"
- " );");
- verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
-
- FormatStyle AlwaysBreak = getLLVMStyle();
- AlwaysBreak.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
- verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
- verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
- verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
- verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
- " ccccccccccccccccccccccccccccccccccccccccccccccc);");
- verifyFormat("template <template <typename> class Fooooooo,\n"
- " template <typename> class Baaaaaaar>\n"
- "struct C {};",
- AlwaysBreak);
- verifyFormat("template <typename T> // T can be A, B or C.\n"
- "struct C {};",
- AlwaysBreak);
- verifyFormat("template <typename T>\n"
- "C(T) noexcept;",
- AlwaysBreak);
- verifyFormat("template <typename T>\n"
- "ClassName(T) noexcept;",
- AlwaysBreak);
- verifyFormat("template <typename T>\n"
- "POOR_NAME(T) noexcept;",
- AlwaysBreak);
- verifyFormat("template <enum E> class A {\n"
- "public:\n"
- " E *f();\n"
- "};");
-
- FormatStyle NeverBreak = getLLVMStyle();
- NeverBreak.BreakTemplateDeclarations = FormatStyle::BTDS_No;
- verifyFormat("template <typename T> class C {};", NeverBreak);
- verifyFormat("template <typename T> void f();", NeverBreak);
- verifyFormat("template <typename T> void f() {}", NeverBreak);
- verifyFormat("template <typename T> C(T) noexcept;", NeverBreak);
- verifyFormat("template <typename T> ClassName(T) noexcept;", NeverBreak);
- verifyFormat("template <typename T> POOR_NAME(T) noexcept;", NeverBreak);
- verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
- "bbbbbbbbbbbbbbbbbbbb) {}",
- NeverBreak);
- verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
- " ccccccccccccccccccccccccccccccccccccccccccccccc);",
- NeverBreak);
- verifyFormat("template <template <typename> class Fooooooo,\n"
- " template <typename> class Baaaaaaar>\n"
- "struct C {};",
- NeverBreak);
- verifyFormat("template <typename T> // T can be A, B or C.\n"
- "struct C {};",
- NeverBreak);
- verifyFormat("template <enum E> class A {\n"
- "public:\n"
- " E *f();\n"
- "};",
- NeverBreak);
- NeverBreak.PenaltyBreakTemplateDeclaration = 100;
- verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
- "bbbbbbbbbbbbbbbbbbbb) {}",
- NeverBreak);
-
- auto Style = getLLVMStyle();
- Style.BreakTemplateDeclarations = FormatStyle::BTDS_Leave;
-
- verifyNoChange("template <typename T>\n"
- "class C {};",
- Style);
- verifyFormat("template <typename T> class C {};", Style);
-
- verifyNoChange("template <typename T>\n"
- "void f();",
- Style);
- verifyFormat("template <typename T> void f();", Style);
-
- verifyNoChange("template <typename T>\n"
- "void f() {}",
- Style);
- verifyFormat("template <typename T> void f() {}", Style);
-
- verifyNoChange("template <typename T>\n"
- "// T can be A, B or C.\n"
- "struct C {};",
- Style);
- verifyFormat("template <typename T> // T can be A, B or C.\n"
- "struct C {};",
- Style);
-
- verifyNoChange("template <typename T>\n"
- "C(T) noexcept;",
- Style);
- verifyFormat("template <typename T> C(T) noexcept;", Style);
-
- verifyNoChange("template <enum E>\n"
- "class A {\n"
- "public:\n"
- " E *f();\n"
- "};",
- Style);
- verifyFormat("template <enum E> class A {\n"
- "public:\n"
- " E *f();\n"
- "};",
- Style);
-
- verifyNoChange("template <auto x>\n"
- "constexpr int simple(int) {\n"
- " char c;\n"
- " return 1;\n"
- "}",
- Style);
- verifyFormat("template <auto x> constexpr int simple(int) {\n"
- " char c;\n"
- " return 1;\n"
- "}",
- Style);
-
- Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
- verifyNoChange("template <auto x>\n"
- "requires(x > 1)\n"
- "constexpr int with_req(int) {\n"
- " return 1;\n"
- "}",
- Style);
- verifyFormat("template <auto x> requires(x > 1)\n"
- "constexpr int with_req(int) {\n"
- " return 1;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
- FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
- Style.ColumnLimit = 60;
- verifyFormat("// Baseline - no comments.\n"
- "template <\n"
- " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
- "void f() {}",
- Style);
-
- verifyFormat("template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
- "void f() {}",
- "template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
- "void f() {}",
- Style);
-
- verifyFormat(
- "template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
- "void f() {}",
- "template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
- "void f() {}",
- Style);
-
- verifyFormat("template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
- " // multiline\n"
- "void f() {}",
- "template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
- " // multiline\n"
- "void f() {}",
- Style);
-
- verifyFormat(
- "template <typename aaaaaaaaaa<\n"
- " bbbbbbbbbbbb>::value> // trailing loooong\n"
- "void f() {}",
- "template <\n"
- " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
- "void f() {}",
- Style);
-}
-
-TEST_F(FormatTest, BreakBeforeTemplateCloser) {
- auto Style = getLLVMStyle();
- // Begin with tests covering the case where there is no constraint on the
- // column limit.
- Style.ColumnLimit = 0;
- Style.BreakBeforeTemplateCloser = true;
- // BreakBeforeTemplateCloser should NOT force template declarations onto
- // multiple lines.
- verifyFormat("template <typename Foo>\n"
- "void foo() {}",
- Style);
- verifyFormat("template <typename Foo, typename Bar>\n"
- "void foo() {}",
- Style);
- // It should add a line break before > if not already present:
- verifyFormat("template <\n"
- " typename Foo\n"
- ">\n"
- "void foo() {}",
- "template <\n"
- " typename Foo>\n"
- "void foo() {}",
- Style);
- verifyFormat("template <\n"
- " typename Foo,\n"
- " typename Bar\n"
- ">\n"
- "void foo() {}",
- "template <\n"
- " typename Foo,\n"
- " typename Bar>\n"
- "void foo() {}",
- Style);
- // When within an indent scope, the > should be placed accordingly:
- verifyFormat("struct Baz {\n"
- " template <\n"
- " typename Foo,\n"
- " typename Bar\n"
- " >\n"
- " void foo() {}\n"
- "};",
- "struct Baz {\n"
- " template <\n"
- " typename Foo,\n"
- " typename Bar>\n"
- " void foo() {}\n"
- "};",
- Style);
-
- // Test from https://github.com/llvm/llvm-project/issues/80049:
- verifyFormat(
- "using type = std::remove_cv_t<\n"
- " add_common_cv_reference<\n"
- " std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
- " T0,\n"
- " T1\n"
- " >\n"
- ">;",
- "using type = std::remove_cv_t<\n"
- " add_common_cv_reference<\n"
- " std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
- " T0,\n"
- " T1>>;",
- Style);
-
- // Test lambda goes to next line:
- verifyFormat("void foo() {\n"
- " auto lambda = []<\n"
- " typename T\n"
- " >(T t) {\n"
- " };\n"
- "}",
- "void foo() {\n"
- " auto lambda = []<\n"
- " typename T>(T t){\n"
- " };\n"
- "}",
- Style);
- // With no column limit, two parameters can go on the same line:
- verifyFormat("void foo() {\n"
- " auto lambda = []<\n"
- " typename T, typename Foo\n"
- " >(T t) {\n"
- " };\n"
- "}",
- "void foo() {\n"
- " auto lambda = []<\n"
- " typename T, typename Foo>(T t){\n"
- " };\n"
- "}",
- Style);
- // Or on different lines:
- verifyFormat("void foo() {\n"
- " auto lambda = []<\n"
- " typename T,\n"
- " typename Foo\n"
- " >(T t) {\n"
- " };\n"
- "}",
- "void foo() {\n"
- " auto lambda = []<\n"
- " typename T,\n"
- " typename Foo>(T t){\n"
- " };\n"
- "}",
- Style);
-
- // Test template usage goes to next line too:
- verifyFormat("void foo() {\n"
- " myFunc<\n"
- " T\n"
- " >();\n"
- "}",
- "void foo() {\n"
- " myFunc<\n"
- " T>();\n"
- "}",
- Style);
-
- // Now test that it handles the cases when the column limit forces wrapping.
- Style.ColumnLimit = 40;
- // The typename goes on the first line if it fits:
- verifyFormat("template <typename Fooooooooooooooooooo,\n"
- " typename Bar>\n"
- "void foo() {}",
- Style);
- verifyFormat("template <typename Foo,\n"
- " typename Barrrrrrrrrrrrrrrrrr>\n"
- "void foo() {}",
- Style);
- // Long names should be split in one step:
- verifyFormat("template <\n"
- " typename Foo,\n"
- " typename Barrrrrrrrrrrrrrrrrrr\n"
- ">\n"
- "void foo() {}",
- "template <typename Foo, typename Barrrrrrrrrrrrrrrrrrr>\n"
- "void foo() {}",
- Style);
- verifyFormat("template <\n"
- " typename Foooooooooooooooooooo,\n"
- " typename Bar\n"
- ">\n"
- "void foo() {}",
- "template <typename Foooooooooooooooooooo, typename Bar>\n"
- "void foo() {}",
- Style);
- // Even when there is only one long name:
- verifyFormat("template <\n"
- " typename Foooooooooooooooooooo\n"
- ">\n"
- "void foo() {}",
- "template <typename Foooooooooooooooooooo>\n"
- "void foo() {}",
- Style);
- // Test lambda goes to next line if the type is looong:
- verifyFormat("void foo() {\n"
- " auto lambda =\n"
- " []<\n"
- " typename Loooooooooooooooooooooooooooooooooong\n"
- " >(T t) {};\n"
- " auto lambda =\n"
- " [looooooooooooooong]<\n"
- " typename Loooooooooooooooooooooooooooooooooong\n"
- " >(T t) {};\n"
- " auto lambda =\n"
- " []<\n"
- " typename T,\n"
- " typename Loooooooooooooooooooooooooooooooooong\n"
- " >(T t) {};\n"
- // Nested:
- " auto lambda =\n"
- " []<\n"
- " template <typename, typename>\n"
- " typename Looooooooooooooooooong\n"
- " >(T t) {};\n"
- // Same idea, the "T" is now short rather than Looong:
- " auto lambda =\n"
- " []<template <typename, typename>\n"
- " typename T>(T t) {};\n"
- // Nested with long capture forces the style to block indent:
- " auto lambda =\n"
- " [loooooooooooooooooooong]<\n"
- " template <typename, typename>\n"
- " typename Looooooooooooooooooong\n"
- " >(T t) {};\n"
- // But *now* it stays block indented even when T is short:
- " auto lambda =\n"
- " [loooooooooooooooooooong]<\n"
- " template <typename, typename>\n"
- " typename T\n"
- " >(T t) {};\n"
- // Nested, with long name and long captures:
- " auto lambda =\n"
- " [loooooooooooooooooooong]<\n"
- " template <\n"
- " typename Foooooooooooooooo,\n"
- " typename\n"
- " >\n"
- " typename T\n"
- " >(T t) {};\n"
- // Allow the nested template to be on the same line:
- " auto lambda =\n"
- " [loooooooooooooooooooong]<\n"
- " template <typename Fooooooooo,\n"
- " typename>\n"
- " typename T\n"
- " >(T t) {};\n"
- "}",
- Style);
-
- // Test template usage goes to next line if the type is looong:
- verifyFormat("void foo() {\n"
- " myFunc<\n"
- " Looooooooooooooooooooooooong\n"
- " >();\n"
- "}",
- Style);
- // Even a single type in the middle is enough to force it to block indent
- // style:
- verifyFormat("void foo() {\n"
- " myFunc<\n"
- " Foo, Foo, Foo,\n"
- " Foooooooooooooooooooooooooooooo,\n"
- " Foo, Foo, Foo, Foo\n"
- " >();\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, WrapsTemplateParameters) {
- FormatStyle Style = getLLVMStyle();
- Style.AlignAfterOpenBracket = false;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
- verifyFormat(
- "template <typename... a> struct q {};\n"
- "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
- " y;",
- Style);
- Style.AlignAfterOpenBracket = false;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat(
- "template <typename... a> struct r {};\n"
- "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
- " y;",
- Style);
- Style.BreakAfterOpenBracketFunction = true;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
- verifyFormat("template <typename... a> struct s {};\n"
- "extern s<\n"
- " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
- "aaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
- "aaaaaaaaaaaaaaaaaaaaaa>\n"
- " y;",
- Style);
- Style.BreakAfterOpenBracketFunction = true;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat("template <typename... a> struct t {};\n"
- "extern t<\n"
- " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
- "aaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
- "aaaaaaaaaaaaaaaaaaaaaa>\n"
- " y;",
- Style);
-}
-
-TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
-
- // FIXME: Should we have the extra indent after the second break?
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
-
- verifyFormat(
- "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
- " cccccccccccccccccccccccccccccccccccccccccccccc());");
-
- // Breaking at nested name specifiers is generally not desirable.
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaa);",
- getLLVMStyleWithColumns(74));
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
-
- verifyFormat(
- "LongClassNameToShowTheIssue::AndAnotherLongClassNameToShowTheIssue::\n"
- " AndAnotherLongClassNameToShowTheIssue() {}\n"
- "LongClassNameToShowTheIssue::AndAnotherLongClassNameToShowTheIssue::\n"
- " ~AndAnotherLongClassNameToShowTheIssue() {}");
-}
-
-TEST_F(FormatTest, UnderstandsTemplateParameters) {
- verifyFormat("A<int> a;");
- verifyFormat("A<A<A<int>>> a;");
- verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
- verifyFormat("bool x = a < 1 || 2 > a;");
- verifyFormat("bool x = 5 < f<int>();");
- verifyFormat("bool x = f<int>() > 5;");
- verifyFormat("bool x = 5 < a<int>::x;");
- verifyFormat("bool x = a < 4 ? a > 2 : false;");
- verifyFormat("bool x = f() ? a < 2 : a > 2;");
-
- verifyGoogleFormat("A<A<int>> a;");
- verifyGoogleFormat("A<A<A<int>>> a;");
- verifyGoogleFormat("A<A<A<A<int>>>> a;");
- verifyGoogleFormat("A<A<int> > a;");
- verifyGoogleFormat("A<A<A<int> > > a;");
- verifyGoogleFormat("A<A<A<A<int> > > > a;");
- verifyGoogleFormat("A<::A<int>> a;");
- verifyGoogleFormat("A<::A> a;");
- verifyGoogleFormat("A< ::A> a;");
- verifyGoogleFormat("A< ::A<int> > a;");
- verifyFormat("A<A<A<A>>> a;", "A<A<A<A> >> a;", getGoogleStyle());
- verifyFormat("A<A<A<A>>> a;", "A<A<A<A>> > a;", getGoogleStyle());
- verifyFormat("A<::A<int>> a;", "A< ::A<int>> a;", getGoogleStyle());
- verifyFormat("A<::A<int>> a;", "A<::A<int> > a;", getGoogleStyle());
- verifyFormat("auto x = [] { A<A<A<A>>> a; };", "auto x=[]{A<A<A<A> >> a;};",
- getGoogleStyle());
-
- verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
-
- // template closer followed by a token that starts with > or =
- verifyFormat("bool b = a<1> > 1;");
- verifyFormat("bool b = a<1> >= 1;");
- verifyFormat("int i = a<1> >> 1;");
- FormatStyle Style = getLLVMStyle();
- Style.SpaceBeforeAssignmentOperators = false;
- verifyFormat("bool b= a<1> == 1;", Style);
- verifyFormat("a<int> = 1;", Style);
- verifyFormat("a<int> >>= 1;", Style);
-
- verifyFormat("test < a | b >> c;");
- verifyFormat("test<test<a | b>> c;");
- verifyFormat("test >> a >> b;");
- verifyFormat("test << a >> b;");
-
- verifyFormat("f<int>();");
- verifyFormat("template <typename T> void f() {}");
- verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
- verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
- "sizeof(char)>::type>;");
- verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
- verifyFormat("f(a.operator()<A>());");
- verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " .template operator()<A>());",
- getLLVMStyleWithColumns(35));
- verifyFormat("bool_constant<a && noexcept(f())>;");
- verifyFormat("bool_constant<a || noexcept(f())>;");
-
- verifyFormat("if (std::tuple_size_v<T> > 0)");
-
- // Not template parameters.
- verifyFormat("return a < b && c > d;");
- verifyFormat("a < 0 ? b : a > 0 ? c : d;");
- verifyFormat("ratio{-1, 2} < ratio{-1, 3} == -1 / 3 > -1 / 2;");
- verifyFormat("void f() {\n"
- " while (a < b && c > d) {\n"
- " }\n"
- "}");
- verifyFormat("template <typename... Types>\n"
- "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
- getLLVMStyleWithColumns(60));
- verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
- verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
- verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
- verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
-
- verifyFormat("#define FOO(typeName, realClass) \\\n"
- " {#typeName, foo<FooType>(new foo<realClass>(#typeName))}",
- getLLVMStyleWithColumns(60));
-}
-
-TEST_F(FormatTest, UnderstandsShiftOperators) {
- verifyFormat("if (i < x >> 1)");
- verifyFormat("while (i < x >> 1)");
- verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
- verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
- verifyFormat(
- "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
- verifyFormat("Foo.call<Bar<Function>>()");
- verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
- verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
- "++i, v = v >> 1)");
- verifyFormat("if (w<u<v<x>>, 1>::t)");
-}
-
-TEST_F(FormatTest, BitshiftOperatorWidth) {
- verifyFormat("int a = 1 << 2; /* foo\n"
- " bar */",
- "int a=1<<2; /* foo\n"
- " bar */");
-
- verifyFormat("int b = 256 >> 1; /* foo\n"
- " bar */",
- "int b =256>>1 ; /* foo\n"
- " bar */");
-}
-
-TEST_F(FormatTest, UnderstandsBinaryOperators) {
- verifyFormat("COMPARE(a, ==, b);");
- verifyFormat("auto s = sizeof...(Ts) - 1;");
-}
-
-TEST_F(FormatTest, UnderstandsPointersToMembers) {
- verifyFormat("int A::*x;");
- verifyFormat("int (S::*func)(void *);");
- verifyFormat("void f() { int (S::*func)(void *); }");
- verifyFormat("typedef bool *(Class::*Member)() const;");
- verifyFormat("void f() {\n"
- " (a->*f)();\n"
- " a->*x;\n"
- " (a.*f)();\n"
- " ((*a).*f)();\n"
- " a.*x;\n"
- "}");
- verifyFormat("void f() {\n"
- " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
- " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
- "}");
- verifyFormat(
- "(aaaaaaaaaa->*bbbbbbb)(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
-
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
- verifyFormat("typedef bool *(Class::*Member)() const;", Style);
- verifyFormat("void f(int A::*p) { int A::*v = &A::B; }", Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("typedef bool* (Class::*Member)() const;", Style);
- verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("typedef bool * (Class::*Member)() const;", Style);
- verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
-}
-
-TEST_F(FormatTest, UnderstandsUnaryOperators) {
- verifyFormat("int a = -2;");
- verifyFormat("f(-1, -2, -3);");
- verifyFormat("a[-1] = 5;");
- verifyFormat("int a = 5 + -2;");
- verifyFormat("if (i == -1) {\n}");
- verifyFormat("if (i != -1) {\n}");
- verifyFormat("if (i > -1) {\n}");
- verifyFormat("if (i < -1) {\n}");
- verifyFormat("++(a->f());");
- verifyFormat("--(a->f());");
- verifyFormat("(a->f())++;");
- verifyFormat("a[42]++;");
- verifyFormat("if (!(a->f())) {\n}");
- verifyFormat("if (!+i) {\n}");
- verifyFormat("~&a;");
- verifyFormat("for (x = 0; -10 < x; --x) {\n}");
- verifyFormat("sizeof -x");
- verifyFormat("sizeof +x");
- verifyFormat("sizeof *x");
- verifyFormat("sizeof &x");
- verifyFormat("delete +x;");
- verifyFormat("co_await +x;");
- verifyFormat("case *x:");
- verifyFormat("case &x:");
-
- verifyFormat("a-- > b;");
- verifyFormat("b ? -a : c;");
- verifyFormat("n * sizeof char16;");
- verifyGoogleFormat("n * alignof char16;");
- verifyFormat("sizeof(char);");
- verifyGoogleFormat("alignof(char);");
-
- verifyFormat("return -1;");
- verifyFormat("throw -1;");
- verifyFormat("switch (a) {\n"
- "case -1:\n"
- " break;\n"
- "}");
- verifyFormat("#define X -1");
- verifyFormat("#define X -kConstant");
-
- verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
- verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
-
- verifyFormat("int a = /* confusing comment */ -1;");
- // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
- verifyFormat("int a = i /* confusing comment */++;");
-
- verifyFormat("co_yield -1;");
- verifyFormat("co_return -1;");
-
- // Check that * is not treated as a binary operator when we set
- // PointerAlignment as PAS_Left after a keyword and not a declaration.
- FormatStyle PASLeftStyle = getLLVMStyle();
- PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("co_return *a;", PASLeftStyle);
- verifyFormat("co_await *a;", PASLeftStyle);
- verifyFormat("co_yield *a", PASLeftStyle);
- verifyFormat("return *a;", PASLeftStyle);
-}
-
-TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
- verifyFormat("if (!aaaaaaaaaa( // break\n"
- " aaaaa)) {\n"
- "}");
- verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
- " aaaaa));");
- verifyFormat("*aaa = aaaaaaa( // break\n"
- " bbbbbb);");
-}
-
-TEST_F(FormatTest, UnderstandsOverloadedOperators) {
- verifyFormat("bool operator<();");
- verifyFormat("bool operator>();");
- verifyFormat("bool operator=();");
- verifyFormat("bool operator==();");
- verifyFormat("bool operator!=();");
- verifyFormat("int operator+();");
- verifyFormat("int operator++();");
- verifyFormat("int operator++(int) volatile noexcept;");
- verifyFormat("bool operator,();");
- verifyFormat("bool operator();");
- verifyFormat("bool operator()();");
- verifyFormat("bool operator[]();");
- verifyFormat("operator bool();");
- verifyFormat("operator int();");
- verifyFormat("operator void *();");
- verifyFormat("operator SomeType<int>();");
- verifyFormat("operator SomeType<int, int>();");
- verifyFormat("operator SomeType<SomeType<int>>();");
- verifyFormat("operator< <>();");
- verifyFormat("operator<< <>();");
- verifyFormat("< <>");
-
- verifyFormat("void *operator new(std::size_t size);");
- verifyFormat("void *operator new[](std::size_t size);");
- verifyFormat("void operator delete(void *ptr);");
- verifyFormat("void operator delete[](void *ptr);");
- verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
- "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
- " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
-
- verifyFormat(
- "ostream &operator<<(ostream &OutputStream,\n"
- " SomeReallyLongType WithSomeReallyLongValue);");
- verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
- " const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
- " return left.group < right.group;\n"
- "}");
- verifyFormat("SomeType &operator=(const SomeType &S);");
- verifyFormat("f.template operator()<int>();");
-
- verifyGoogleFormat("operator void*();");
- verifyGoogleFormat("operator SomeType<SomeType<int>>();");
- verifyGoogleFormat("operator ::A();");
-
- verifyFormat("using A::operator+;");
- verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
- "int i;");
-
- // Calling an operator as a member function.
- verifyFormat("void f() { a.operator*(); }");
- verifyFormat("void f() { a.operator*(b & b); }");
- verifyFormat("void f() { a->operator&(a * b); }");
- verifyFormat("void f() { NS::a.operator+(*b * *b); }");
- verifyFormat("void f() { operator*(a & a); }");
- verifyFormat("void f() { operator&(a, b * b); }");
-
- verifyFormat("void f() { return operator()(x) * b; }");
- verifyFormat("void f() { return operator[](x) * b; }");
- verifyFormat("void f() { return operator\"\"_a(x) * b; }");
- verifyFormat("void f() { return operator\"\" _a(x) * b; }");
- verifyFormat("void f() { return operator\"\"s(x) * b; }");
- verifyFormat("void f() { return operator\"\" s(x) * b; }");
- verifyFormat("void f() { return operator\"\"if(x) * b; }");
-
- verifyFormat("::operator delete(foo);");
- verifyFormat("::operator new(n * sizeof(foo));");
- verifyFormat("foo() { ::operator delete(foo); }");
- verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
-}
-
-TEST_F(FormatTest, SpaceBeforeTemplateCloser) {
- verifyFormat("C<&operator- > minus;");
- verifyFormat("C<&operator> > gt;");
- verifyFormat("C<&operator>= > ge;");
- verifyFormat("C<&operator<= > le;");
- verifyFormat("C<&operator< <X>> lt;");
-}
-
-TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
- verifyFormat("void A::b() && {}");
- verifyFormat("void A::b() && noexcept {}");
- verifyFormat("Deleted &operator=(const Deleted &) & = default;");
- verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
- verifyFormat("Deleted &operator=(const Deleted &) & noexcept = default;");
- verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
- verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
- verifyFormat("Deleted &operator=(const Deleted &) &;");
- verifyFormat("Deleted &operator=(const Deleted &) &&;");
- verifyFormat("SomeType MemberFunction(const Deleted &) &;");
- verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
- verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
- verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
- verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
- verifyFormat("SomeType MemberFunction(const Deleted &) && noexcept {}");
- verifyFormat("void Fn(T const &) const &;");
- verifyFormat("void Fn(T const volatile &&) const volatile &&;");
- verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;");
- verifyGoogleFormat("template <typename T>\n"
- "void F(T) && = delete;");
- verifyFormat("template <typename T> void operator=(T) &;");
- verifyFormat("template <typename T> void operator=(T) const &;");
- verifyFormat("template <typename T> void operator=(T) & noexcept;");
- verifyFormat("template <typename T> void operator=(T) & = default;");
- verifyFormat("template <typename T> void operator=(T) &&;");
- verifyFormat("template <typename T> void operator=(T) && = delete;");
- verifyFormat("template <typename T> void operator=(T) & {}");
- verifyFormat("template <typename T> void operator=(T) && {}");
-
- FormatStyle AlignLeft = getLLVMStyle();
- AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("void A::b() && {}", AlignLeft);
- verifyFormat("void A::b() && noexcept {}", AlignLeft);
- verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
- verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
- AlignLeft);
- verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
- AlignLeft);
- verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
- verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
- verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
- verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
- verifyFormat("auto Function(T) & -> void {}", AlignLeft);
- verifyFormat("auto Function(T) & -> void;", AlignLeft);
- verifyFormat("void Fn(T const&) const&;", AlignLeft);
- verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
- verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
- AlignLeft);
- verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
- verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
- verifyFormat("template <typename T> void operator=(T) & noexcept;",
- AlignLeft);
- verifyFormat("template <typename T> void operator=(T) & = default;",
- AlignLeft);
- verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
- verifyFormat("template <typename T> void operator=(T) && = delete;",
- AlignLeft);
- verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
- verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
- verifyFormat("for (foo<void() &&>& cb : X)", AlignLeft);
-
- FormatStyle AlignMiddle = getLLVMStyle();
- AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("void A::b() && {}", AlignMiddle);
- verifyFormat("void A::b() && noexcept {}", AlignMiddle);
- verifyFormat("Deleted & operator=(const Deleted &) & = default;",
- AlignMiddle);
- verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
- AlignMiddle);
- verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
- AlignMiddle);
- verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
- verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
- verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
- verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
- verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
- verifyFormat("auto Function(T) & -> void;", AlignMiddle);
- verifyFormat("void Fn(T const &) const &;", AlignMiddle);
- verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
- verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
- AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) & noexcept;",
- AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) & = default;",
- AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) && = delete;",
- AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
- verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.InCStyleCasts = true;
- verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
- verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
- verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
- verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
-
- Spaces.SpacesInParensOptions.InCStyleCasts = false;
- Spaces.SpacesInParensOptions.Other = true;
- verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
- verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
- Spaces);
- verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
- verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
-
- FormatStyle BreakTemplate = getLLVMStyle();
- BreakTemplate.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int &foo(const std::string &str) & noexcept {}\n"
- "};",
- BreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int &foo(const std::string &str) && noexcept {}\n"
- "};",
- BreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int &foo(const std::string &str) const & noexcept {}\n"
- "};",
- BreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int &foo(const std::string &str) const & noexcept {}\n"
- "};",
- BreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " auto foo(const std::string &str) && noexcept -> int & {}\n"
- "};",
- BreakTemplate);
-
- FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
- AlignLeftBreakTemplate.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
- AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int& foo(const std::string& str) & noexcept {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int& foo(const std::string& str) && noexcept {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int& foo(const std::string& str) const& noexcept {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " int& foo(const std::string& str) const&& noexcept {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " auto foo(const std::string& str) && noexcept -> int& {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- // The `&` in `Type&` should not be confused with a trailing `&` of
- // DEPRECATED(reason) member function.
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " DEPRECATED(reason)\n"
- " Type &foo(arguments) {}\n"
- "};",
- BreakTemplate);
-
- verifyFormat("struct f {\n"
- " template <class T>\n"
- " DEPRECATED(reason)\n"
- " Type& foo(arguments) {}\n"
- "};",
- AlignLeftBreakTemplate);
-
- verifyFormat("void (*foopt)(int) = &func;");
-
- FormatStyle DerivePointerAlignment = getLLVMStyle();
- DerivePointerAlignment.DerivePointerAlignment = true;
- // There's always a space between the function and its trailing qualifiers.
- // This isn't evidence for PAS_Right (or for PAS_Left).
- std::string Prefix = "void a() &;\n"
- "void b() &;\n";
- verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
- verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
- // Same if the function is an overloaded operator, and with &&.
- Prefix = "void operator()() &&;\n"
- "void operator()() &&;\n";
- verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
- verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
- // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
- Prefix = "void a() const &;\n"
- "void b() const &;\n";
- verifyFormat(Prefix + "int *x;", Prefix + "int* x;", DerivePointerAlignment);
-
- constexpr StringRef Code("MACRO(int*, std::function<void() &&>);");
- verifyFormat(Code, DerivePointerAlignment);
-
- auto Style = getGoogleStyle();
- Style.DerivePointerAlignment = true;
- verifyFormat(Code, Style);
-}
-
-TEST_F(FormatTest, PointerAlignmentFallback) {
- FormatStyle Style = getLLVMStyle();
- Style.DerivePointerAlignment = true;
-
- constexpr StringRef Code("int* p;\n"
- "int *q;\n"
- "int * r;");
-
- EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
- verifyFormat("int *p;\n"
- "int *q;\n"
- "int *r;",
- Code, Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("int* p;\n"
- "int* q;\n"
- "int* r;",
- Code, Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("int * p;\n"
- "int * q;\n"
- "int * r;",
- Code, Style);
-}
-
-TEST_F(FormatTest, UnderstandsNewAndDelete) {
- verifyFormat("A(void *p) : a(new (p) int) {}");
- verifyFormat("void f() {\n"
- " A *a = new A;\n"
- " A *a = new (placement) A;\n"
- " delete a;\n"
- " delete (A *)a;\n"
- "}");
- verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
- " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
- " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("delete[] h->p;");
- verifyFormat("delete[] (void *)p;");
-
- verifyFormat("void operator delete(void *foo) ATTRIB;");
- verifyFormat("void operator new(void *foo) ATTRIB;");
- verifyFormat("void operator delete[](void *foo) ATTRIB;");
- verifyFormat("void operator delete(void *ptr) noexcept;");
-
- verifyFormat("void new(link p);\n"
- "void delete(link p);",
- "void new (link p);\n"
- "void delete (link p);",
- getLLVMStyle(FormatStyle::LK_C));
-
- verifyFormat("{\n"
- " p->new();\n"
- "}\n"
- "{\n"
- " p->delete();\n"
- "}",
- "{\n"
- " p->new ();\n"
- "}\n"
- "{\n"
- " p->delete ();\n"
- "}");
-
- FormatStyle AfterPlacementOperator = getLLVMStyle();
- AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- EXPECT_TRUE(
- AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator);
- verifyFormat("new (buf) int;", AfterPlacementOperator);
- verifyFormat("struct A {\n"
- " int *a;\n"
- " A(int *p) : a(new (p) int) {\n"
- " new (p) int;\n"
- " int *b = new (p) int;\n"
- " int *c = new (p) int(3);\n"
- " delete (b);\n"
- " }\n"
- "};",
- AfterPlacementOperator);
- verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
- verifyFormat("delete (int *)p;", AfterPlacementOperator);
-
- AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
- false;
- verifyFormat("new(buf) int;", AfterPlacementOperator);
- verifyFormat("struct A {\n"
- " int *a;\n"
- " A(int *p) : a(new(p) int) {\n"
- " new(p) int;\n"
- " int *b = new(p) int;\n"
- " int *c = new(p) int(3);\n"
- " delete(b);\n"
- " }\n"
- "};",
- AfterPlacementOperator);
- verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
- verifyFormat("delete (int *)p;", AfterPlacementOperator);
-}
-
-TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
- verifyFormat("int *f(int *a) {}");
- verifyFormat("int main(int argc, char **argv) {}");
- verifyFormat("Test::Test(int b) : a(b * b) {}");
- verifyIndependentOfContext("f(a, *a);");
- verifyFormat("void g() { f(*a); }");
- verifyIndependentOfContext("int a = b * 10;");
- verifyIndependentOfContext("int a = 10 * b;");
- verifyIndependentOfContext("int a = b * c;");
- verifyIndependentOfContext("int a += b * c;");
- verifyIndependentOfContext("int a -= b * c;");
- verifyIndependentOfContext("int a *= b * c;");
- verifyIndependentOfContext("int a /= b * c;");
- verifyIndependentOfContext("int a = *b;");
- verifyIndependentOfContext("int a = *b * c;");
- verifyIndependentOfContext("int a = b * *c;");
- verifyIndependentOfContext("int a = b * (10);");
- verifyIndependentOfContext("S << b * (10);");
- verifyIndependentOfContext("return 10 * b;");
- verifyIndependentOfContext("return *b * *c;");
- verifyIndependentOfContext("return a & ~b;");
- verifyIndependentOfContext("f(b ? *c : *d);");
- verifyIndependentOfContext("int a = b ? *c : *d;");
- verifyIndependentOfContext("*b = a;");
- verifyIndependentOfContext("a * ~b;");
- verifyIndependentOfContext("a * !b;");
- verifyIndependentOfContext("a * +b;");
- verifyIndependentOfContext("a * -b;");
- verifyIndependentOfContext("a * ++b;");
- verifyIndependentOfContext("a * --b;");
- verifyIndependentOfContext("a[4] * b;");
- verifyIndependentOfContext("a[a * a] = 1;");
- verifyIndependentOfContext("f() * b;");
- verifyIndependentOfContext("a * [self dostuff];");
- verifyIndependentOfContext("int x = a * (a + b);");
- verifyIndependentOfContext("(a *)(a + b);");
- verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
- verifyIndependentOfContext("int *pa = (int *)&a;");
- verifyIndependentOfContext("return sizeof(int **);");
- verifyIndependentOfContext("return sizeof(int ******);");
- verifyIndependentOfContext("return (int **&)a;");
- verifyIndependentOfContext("f((*PointerToArray)[10]);");
- verifyFormat("void f(Type (*parameter)[10]) {}");
- verifyFormat("void f(Type (¶meter)[10]) {}");
- verifyGoogleFormat("return sizeof(int**);");
- verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
- verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
- verifyFormat("auto a = [](int **&, int ***) {};");
- verifyFormat("auto PointerBinding = [](const char *S) {};");
- verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
- verifyFormat("[](const decltype(*a) &value) {}");
- verifyFormat("[](const typeof(*a) &value) {}");
- verifyFormat("[](const _Atomic(a *) &value) {}");
- verifyFormat("[](const __underlying_type(a) &value) {}");
- verifyFormat("decltype(a * b) F();");
- verifyFormat("typeof(a * b) F();");
- verifyFormat("#define MACRO() [](A *a) { return 1; }");
- verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
- verifyIndependentOfContext("typedef void (*f)(int *a);");
- verifyIndependentOfContext("typedef void (*f)(Type *a);");
- verifyIndependentOfContext("int i{a * b};");
- verifyIndependentOfContext("aaa && aaa->f();");
- verifyIndependentOfContext("int x = ~*p;");
- verifyFormat("Constructor() : a(a), area(width * height) {}");
- verifyFormat("Constructor() : a(a), area(a, width * height) {}");
- verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
- verifyFormat("void f() { f(a, c * d); }");
- verifyFormat("void f() { f(new a(), c * d); }");
- verifyFormat("void f(const MyOverride &override);");
- verifyFormat("void f(const MyFinal &final);");
- verifyIndependentOfContext("bool a = f() && override.f();");
- verifyIndependentOfContext("bool a = f() && final.f();");
-
- verifyIndependentOfContext("InvalidRegions[*R] = 0;");
-
- verifyIndependentOfContext("A<int *> a;");
- verifyIndependentOfContext("A<int **> a;");
- verifyIndependentOfContext("A<int *, int *> a;");
- verifyIndependentOfContext("A<int *[]> a;");
- verifyIndependentOfContext(
- "const char *const p = reinterpret_cast<const char *const>(q);");
- verifyIndependentOfContext("A<int **, int **> a;");
- verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
- verifyFormat("for (char **a = b; *a; ++a) {\n}");
- verifyFormat("for (; a && b;) {\n}");
- verifyFormat("bool foo = true && [] { return false; }();");
-
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyGoogleFormat("int const* a = &b;");
- verifyGoogleFormat("**outparam = 1;");
- verifyGoogleFormat("*outparam = a * b;");
- verifyGoogleFormat("int main(int argc, char** argv) {}");
- verifyGoogleFormat("A<int*> a;");
- verifyGoogleFormat("A<int**> a;");
- verifyGoogleFormat("A<int*, int*> a;");
- verifyGoogleFormat("A<int**, int**> a;");
- verifyGoogleFormat("f(b ? *c : *d);");
- verifyGoogleFormat("int a = b ? *c : *d;");
- verifyGoogleFormat("Type* t = **x;");
- verifyGoogleFormat("Type* t = *++*x;");
- verifyGoogleFormat("*++*x;");
- verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
- verifyGoogleFormat("Type* t = x++ * y;");
- verifyGoogleFormat(
- "const char* const p = reinterpret_cast<const char* const>(q);");
- verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
- verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
- verifyGoogleFormat("template <typename T>\n"
- "void f(int i = 0, SomeType** temps = NULL);");
-
- FormatStyle Left = getLLVMStyle();
- Left.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("x = *a(x) = *a(y);", Left);
- verifyFormat("for (;; *a = b) {\n}", Left);
- verifyFormat("return *this += 1;", Left);
- verifyFormat("throw *x;", Left);
- verifyFormat("delete *x;", Left);
- verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
- verifyFormat("[](const decltype(*a)* ptr) {}", Left);
- verifyFormat("[](const typeof(*a)* ptr) {}", Left);
- verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
- verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
- verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
- verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
- verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
- verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
-
- verifyIndependentOfContext("a = *(x + y);");
- verifyIndependentOfContext("a = &(x + y);");
- verifyIndependentOfContext("*(x + y).call();");
- verifyIndependentOfContext("&(x + y)->call();");
- verifyFormat("void f() { &(*I).first; }");
-
- verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
- verifyFormat("f(* /* confusing comment */ foo);");
- verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
- verifyFormat("void foo(int * // this is the first paramters\n"
- " ,\n"
- " int second);");
- verifyFormat("double term = a * // first\n"
- " b;");
- verifyFormat(
- "int *MyValues = {\n"
- " *A, // Operator detection might be confused by the '{'\n"
- " *BB // Operator detection might be confused by previous comment\n"
- "};");
-
- verifyIndependentOfContext("if (int *a = &b)");
- verifyIndependentOfContext("if (int &a = *b)");
- verifyIndependentOfContext("if (a & b[i])");
- verifyIndependentOfContext("if constexpr (a & b[i])");
- verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
- verifyIndependentOfContext("if (a * (b * c))");
- verifyIndependentOfContext("if constexpr (a * (b * c))");
- verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
- verifyIndependentOfContext("if (a::b::c::d & b[i])");
- verifyIndependentOfContext("if (*b[i])");
- verifyIndependentOfContext("if (int *a = (&b))");
- verifyIndependentOfContext("while (int *a = &b)");
- verifyIndependentOfContext("while (a * (b * c))");
- verifyIndependentOfContext("size = sizeof *a;");
- verifyIndependentOfContext("if (a && (b = c))");
- verifyFormat("void f() {\n"
- " for (const int &v : Values) {\n"
- " }\n"
- "}");
- verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
- verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
- verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
-
- verifyFormat("#define A (!a * b)");
- verifyFormat("#define MACRO \\\n"
- " int *i = a * b; \\\n"
- " void f(a *b);",
- getLLVMStyleWithColumns(19));
-
- verifyIndependentOfContext("A = new SomeType *[Length];");
- verifyIndependentOfContext("A = new SomeType *[Length]();");
- verifyIndependentOfContext("T **t = new T *;");
- verifyIndependentOfContext("T **t = new T *();");
- verifyGoogleFormat("A = new SomeType*[Length]();");
- verifyGoogleFormat("A = new SomeType*[Length];");
- verifyGoogleFormat("T** t = new T*;");
- verifyGoogleFormat("T** t = new T*();");
-
- verifyFormat("STATIC_ASSERT((a & b) == 0);");
- verifyFormat("STATIC_ASSERT(0 == (a & b));");
- verifyFormat("template <bool a, bool b> "
- "typename t::if<x && y>::type f() {}");
- verifyFormat("template <int *y> f() {}");
- verifyFormat("vector<int *> v;");
- verifyFormat("vector<int *const> v;");
- verifyFormat("vector<int *const **const *> v;");
- verifyFormat("vector<int *volatile> v;");
- verifyFormat("vector<a *_Nonnull> v;");
- verifyFormat("vector<a *_Nullable> v;");
- verifyFormat("vector<a *_Null_unspecified> v;");
- verifyGoogleFormat("vector<a* absl_nonnull> v;");
- verifyGoogleFormat("vector<a* absl_nullable> v;");
- verifyGoogleFormat("vector<a* absl_nullability_unknown> v;");
- verifyFormat("vector<a *__ptr32> v;");
- verifyFormat("vector<a *__ptr64> v;");
- verifyFormat("vector<a *__capability> v;");
- FormatStyle TypeMacros = getLLVMStyle();
- TypeMacros.TypenameMacros = {"LIST"};
- verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
- verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
- verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
- verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
- verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
-
- FormatStyle CustomQualifier = getLLVMStyle();
- // Add identifiers that should not be parsed as a qualifier by default.
- CustomQualifier.AttributeMacros.push_back("__my_qualifier");
- CustomQualifier.AttributeMacros.push_back("_My_qualifier");
- CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
- verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
- verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
- verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
- verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
- verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
- verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
- verifyFormat("vector<a * _NotAQualifier> v;");
- verifyFormat("vector<a * __not_a_qualifier> v;");
- verifyFormat("vector<a * b> v;");
- verifyFormat("foo<b && false>();");
- verifyFormat("foo<b & 1>();");
- verifyFormat("foo<b & (1)>();");
- verifyFormat("foo<b & (~0)>();");
- verifyFormat("foo<b & (true)>();");
- verifyFormat("foo<b & ((1))>();");
- verifyFormat("foo<b & (/*comment*/ 1)>();");
- verifyFormat("decltype(*::std::declval<const T &>()) void F();");
- verifyFormat("typeof(*::std::declval<const T &>()) void F();");
- verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
- verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
- verifyFormat(
- "template <class T, class = typename std::enable_if<\n"
- " std::is_integral<T>::value &&\n"
- " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
- "void F();",
- getLLVMStyleWithColumns(70));
- verifyFormat("template <class T,\n"
- " class = typename std::enable_if<\n"
- " std::is_integral<T>::value &&\n"
- " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
- " class U>\n"
- "void F();",
- getLLVMStyleWithColumns(70));
- verifyFormat(
- "template <class T,\n"
- " class = typename ::std::enable_if<\n"
- " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
- "void F();",
- getGoogleStyleWithColumns(68));
-
- FormatStyle Style = getLLVMStyle();
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("struct {\n"
- "}* ptr;",
- Style);
- verifyFormat("union {\n"
- "}* ptr;",
- Style);
- verifyFormat("class {\n"
- "}* ptr;",
- Style);
- // Don't confuse a multiplication after a brace-initialized expression with
- // a class pointer.
- verifyFormat("int i = int{42} * 34;", Style);
- verifyFormat("struct {\n"
- "}&& ptr = {};",
- Style);
- verifyFormat("union {\n"
- "}&& ptr = {};",
- Style);
- verifyFormat("class {\n"
- "}&& ptr = {};",
- Style);
- verifyFormat("bool b = 3 == int{3} && true;");
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("struct {\n"
- "} * ptr;",
- Style);
- verifyFormat("union {\n"
- "} * ptr;",
- Style);
- verifyFormat("class {\n"
- "} * ptr;",
- Style);
- verifyFormat("struct {\n"
- "} && ptr = {};",
- Style);
- verifyFormat("union {\n"
- "} && ptr = {};",
- Style);
- verifyFormat("class {\n"
- "} && ptr = {};",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Right;
- verifyFormat("struct {\n"
- "} *ptr;",
- Style);
- verifyFormat("union {\n"
- "} *ptr;",
- Style);
- verifyFormat("class {\n"
- "} *ptr;",
- Style);
- verifyFormat("struct {\n"
- "} &&ptr = {};",
- Style);
- verifyFormat("union {\n"
- "} &&ptr = {};",
- Style);
- verifyFormat("class {\n"
- "} &&ptr = {};",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("delete[] *ptr;", Style);
- verifyFormat("delete[] **ptr;", Style);
- verifyFormat("delete[] *(ptr);", Style);
-
- verifyIndependentOfContext("MACRO(int *i);");
- verifyIndependentOfContext("MACRO(auto *a);");
- verifyIndependentOfContext("MACRO(const A *a);");
- verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
- verifyIndependentOfContext("MACRO(decltype(A) *a);");
- verifyIndependentOfContext("MACRO(typeof(A) *a);");
- verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
- verifyIndependentOfContext("MACRO(A *const a);");
- verifyIndependentOfContext("MACRO(A *restrict a);");
- verifyIndependentOfContext("MACRO(A *__restrict__ a);");
- verifyIndependentOfContext("MACRO(A *__restrict a);");
- verifyIndependentOfContext("MACRO(A *volatile a);");
- verifyIndependentOfContext("MACRO(A *__volatile a);");
- verifyIndependentOfContext("MACRO(A *__volatile__ a);");
- verifyIndependentOfContext("MACRO(A *_Nonnull a);");
- verifyIndependentOfContext("MACRO(A *_Nullable a);");
- verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
-
- Style = getGoogleStyle();
- verifyIndependentOfContext("MACRO(A* absl_nonnull a);", Style);
- verifyIndependentOfContext("MACRO(A* absl_nullable a);", Style);
- verifyIndependentOfContext("MACRO(A* absl_nullability_unknown a);", Style);
-
- verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
- verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
- verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
- verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
- verifyIndependentOfContext("MACRO(A *__ptr32 a);");
- verifyIndependentOfContext("MACRO(A *__ptr64 a);");
- verifyIndependentOfContext("MACRO(A *__capability);");
- verifyIndependentOfContext("MACRO(A &__capability);");
- verifyFormat("MACRO(A *__my_qualifier);"); // type declaration
- verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
- // If we add __my_qualifier to AttributeMacros it should always be parsed as
- // a type declaration:
- verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
- verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
- // Also check that TypenameMacros prevents parsing it as multiplication:
- verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
- verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
-
- verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
- verifyFormat("void f() { f(float{1}, a * a); }");
- verifyFormat("void f() { f(float(1), a * a); }");
-
- verifyFormat("f((void (*)(int))g);");
- verifyFormat("f((void (&)(int))g);");
- verifyFormat("f((void (^)(int))g);");
-
- // FIXME: Is there a way to make this work?
- // verifyIndependentOfContext("MACRO(A *a);");
- verifyFormat("MACRO(A &B);");
- verifyFormat("MACRO(A *B);");
- verifyFormat("void f() { MACRO(A * B); }");
- verifyFormat("void f() { MACRO(A & B); }");
-
- // This lambda was mis-formatted after D88956 (treating it as a binop):
- verifyFormat("auto x = [](const decltype(x) &ptr) {};");
- verifyFormat("auto x = [](const decltype(x) *ptr) {};");
- verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
- verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
-
- verifyFormat("DatumHandle const *operator->() const { return input_; }");
- verifyFormat("return options != nullptr && operator==(*options);");
-
- verifyFormat("#define OP(x) \\\n"
- " ostream &operator<<(ostream &s, const A &a) { \\\n"
- " return s << a.DebugString(); \\\n"
- " }",
- "#define OP(x) \\\n"
- " ostream &operator<<(ostream &s, const A &a) { \\\n"
- " return s << a.DebugString(); \\\n"
- " }",
- getLLVMStyleWithColumns(50));
-
- verifyFormat("#define FOO \\\n"
- " void foo() { \\\n"
- " operator+(a * b); \\\n"
- " }",
- getLLVMStyleWithColumns(25));
-
- // FIXME: We cannot handle this case yet; we might be able to figure out that
- // foo<x> d > v; doesn't make sense.
- verifyFormat("foo<a<b && c> d> v;");
-
- FormatStyle PointerMiddle = getLLVMStyle();
- PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("delete *x;", PointerMiddle);
- verifyFormat("int * x;", PointerMiddle);
- verifyFormat("int *[] x;", PointerMiddle);
- verifyFormat("template <int * y> f() {}", PointerMiddle);
- verifyFormat("int * f(int * a) {}", PointerMiddle);
- verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
- verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
- verifyFormat("A<int *> a;", PointerMiddle);
- verifyFormat("A<int **> a;", PointerMiddle);
- verifyFormat("A<int *, int *> a;", PointerMiddle);
- verifyFormat("A<int *[]> a;", PointerMiddle);
- verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
- verifyFormat("A = new SomeType *[Length];", PointerMiddle);
- verifyFormat("T ** t = new T *;", PointerMiddle);
-
- // Member function reference qualifiers aren't binary operators.
- verifyFormat("string // break\n"
- "operator()() & {}");
- verifyFormat("string // break\n"
- "operator()() && {}");
- verifyGoogleFormat("template <typename T>\n"
- "auto x() & -> int {}");
-
- // Should be binary operators when used as an argument expression (overloaded
- // operator invoked as a member function).
- verifyFormat("void f() { a.operator()(a * a); }");
- verifyFormat("void f() { a->operator()(a & a); }");
- verifyFormat("void f() { a.operator()(*a & *a); }");
- verifyFormat("void f() { a->operator()(*a * *a); }");
-
- verifyFormat("int operator()(T (&&)[N]) { return 1; }");
- verifyFormat("int operator()(T (&)[N]) { return 0; }");
-
- verifyFormat("val1 & val2;");
- verifyFormat("val1 & val2 & val3;");
- verifyFormat("class c {\n"
- " void func(type &a) { a & member; }\n"
- " anotherType &member;\n"
- "}");
-}
-
-TEST_F(FormatTest, UnderstandsAttributes) {
- verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
- "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
- verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
- FormatStyle AfterType = getLLVMStyle();
- AfterType.BreakAfterReturnType = FormatStyle::RTBS_All;
- verifyFormat("__attribute__((nodebug)) void\n"
- "foo() {}",
- AfterType);
- verifyFormat("__unused void\n"
- "foo() {}",
- AfterType);
-
- FormatStyle CustomAttrs = getLLVMStyle();
- CustomAttrs.AttributeMacros.push_back("my_attr_name");
- verifyFormat("void MyGoodOldFunction(\n"
- " void *const long_enough = nullptr,\n"
- " void *my_attr_name even_longeeeeeeeeeeeeeeeeer = nullptr);",
- CustomAttrs);
-
- CustomAttrs.AttributeMacros.push_back("__unused");
- CustomAttrs.AttributeMacros.push_back("__attr1");
- CustomAttrs.AttributeMacros.push_back("__attr2");
- CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
- verifyFormat("vector<SomeType *__attribute((foo))> v;");
- verifyFormat("vector<SomeType *__attribute__((foo))> v;");
- verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
- // Check that it is parsed as a multiplication without AttributeMacros and
- // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
- verifyFormat("vector<SomeType * __attr1> v;");
- verifyFormat("vector<SomeType __attr1 *> v;");
- verifyFormat("vector<SomeType __attr1 *const> v;");
- verifyFormat("vector<SomeType __attr1 * __attr2> v;");
- verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
- verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
- verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
- verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
- verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
- verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
- verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
- verifyFormat("__attr1 ::qualified_type f();", CustomAttrs);
- verifyFormat("__attr1() ::qualified_type f();", CustomAttrs);
- verifyFormat("__attr1(nodebug) ::qualified_type f();", CustomAttrs);
-
- // Check that these are not parsed as function declarations:
- CustomAttrs.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle();
- CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
- verifyFormat("SomeType s(InitValue);", CustomAttrs);
- verifyFormat("SomeType s{InitValue};", CustomAttrs);
- verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
- verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
- verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
- verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
- verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
- verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
- verifyGoogleFormat("SomeType* absl_nonnull s(InitValue);");
- verifyGoogleFormat("SomeType* absl_nonnull s{InitValue};");
- verifyGoogleFormat("SomeType* absl_nullable s(InitValue);");
- verifyGoogleFormat("SomeType* absl_nullable s{InitValue};");
- verifyGoogleFormat("SomeType* absl_nullability_unknown s(InitValue);");
- verifyGoogleFormat("SomeType* absl_nullability_unknown s{InitValue};");
-
- auto Style = getLLVMStyleWithColumns(60);
- Style.AttributeMacros.push_back("my_fancy_attr");
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("void foo(const MyLongTypeNameeeeeeeeeeeee* my_fancy_attr\n"
- " testttttttttt);",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
- // Check that qualifiers on pointers don't break parsing of casts.
- verifyFormat("x = (foo *const)*v;");
- verifyFormat("x = (foo *volatile)*v;");
- verifyFormat("x = (foo *restrict)*v;");
- verifyFormat("x = (foo *__attribute__((foo)))*v;");
- verifyFormat("x = (foo *_Nonnull)*v;");
- verifyFormat("x = (foo *_Nullable)*v;");
- verifyFormat("x = (foo *_Null_unspecified)*v;");
- verifyGoogleFormat("x = (foo* absl_nonnull)*v;");
- verifyGoogleFormat("x = (foo* absl_nullable)*v;");
- verifyGoogleFormat("x = (foo* absl_nullability_unknown)*v;");
- verifyFormat("x = (foo *[[clang::attr]])*v;");
- verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
- verifyFormat("x = (foo *__ptr32)*v;");
- verifyFormat("x = (foo *__ptr64)*v;");
- verifyFormat("x = (foo *__capability)*v;");
-
- // Check that we handle multiple trailing qualifiers and skip them all to
- // determine that the expression is a cast to a pointer type.
- FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
- FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
- LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
- StringRef AllQualifiers =
- "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
- "_Nullable [[clang::attr]] __ptr32 __ptr64 __capability";
- verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
- verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
-
- // Also check that address-of is not parsed as a binary bitwise-and:
- verifyFormat("x = (foo *const)&v;");
- verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
- verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
-
- // Check custom qualifiers:
- FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
- CustomQualifier.AttributeMacros.push_back("__my_qualifier");
- verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
- verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
- verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
- CustomQualifier);
- verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
- CustomQualifier);
-
- // Check that unknown identifiers result in binary operator parsing:
- verifyFormat("x = (foo * __unknown_qualifier) * v;");
- verifyFormat("x = (foo * __unknown_qualifier) & v;");
-}
-
-TEST_F(FormatTest, UnderstandsSquareAttributes) {
- verifyFormat("SomeType s [[unused]] (InitValue);");
- verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
- verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
- verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
- verifyFormat("[[suppress(type.5)]] int uninitialized_on_purpose;");
- verifyFormat("void f() [[deprecated(\"so sorry\")]];");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
- verifyFormat("[[nodiscard]] bool f() { return false; }");
- verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}");
- verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}");
- verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}");
- verifyFormat("[[nodiscard]] ::qualified_type f();");
-
- // Make sure we do not mistake attributes for array subscripts.
- verifyFormat("int a() {}\n"
- "[[unused]] int b() {}");
- verifyFormat("NSArray *arr;\n"
- "arr[[Foo() bar]];");
-
- // On the other hand, we still need to correctly find array subscripts.
- verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
-
- // Make sure that we do not mistake Objective-C method inside array literals
- // as attributes, even if those method names are also keywords.
- verifyFormat("@[ [foo bar] ];");
- verifyFormat("@[ [NSArray class] ];");
- verifyFormat("@[ [foo enum] ];");
-
- verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
-
- // Make sure we do not parse attributes as lambda introducers.
- FormatStyle MultiLineFunctions = getLLVMStyle();
- MultiLineFunctions.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle();
- verifyFormat("[[unused]] int b() {\n"
- " return 42;\n"
- "}",
- MultiLineFunctions);
-}
-
-TEST_F(FormatTest, AttributeClass) {
- FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
- verifyFormat("class S {\n"
- " S(S&&) = default;\n"
- "};",
- Style);
- verifyFormat("class [[nodiscard]] S {\n"
- " S(S&&) = default;\n"
- "};",
- Style);
- verifyFormat("class __attribute((maybeunused)) S {\n"
- " S(S&&) = default;\n"
- "};",
- Style);
- verifyFormat("struct S {\n"
- " S(S&&) = default;\n"
- "};",
- Style);
- verifyFormat("struct [[nodiscard]] S {\n"
- " S(S&&) = default;\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, AttributesAfterMacro) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("MACRO;\n"
- "__attribute__((maybe_unused)) int foo() {\n"
- " //...\n"
- "}");
-
- verifyFormat("MACRO;\n"
- "[[nodiscard]] int foo() {\n"
- " //...\n"
- "}");
-
- verifyNoChange("MACRO\n\n"
- "__attribute__((maybe_unused)) int foo() {\n"
- " //...\n"
- "}");
-
- verifyNoChange("MACRO\n\n"
- "[[nodiscard]] int foo() {\n"
- " //...\n"
- "}");
-}
-
-TEST_F(FormatTest, AttributePenaltyBreaking) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
- " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
- Style);
- verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
- " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
- Style);
- verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
- "shared_ptr<ALongTypeName> &C d) {\n}",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandsEllipsis) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("int printf(const char *fmt, ...);");
- verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
- verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
-
- verifyFormat("template <int *...PP> a;", Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
-
- verifyFormat("template <int*... PP> a;", Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("template <int *... PP> a;", Style);
-}
-
-TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
- auto Style = getGoogleStyle();
- EXPECT_FALSE(Style.DerivePointerAlignment);
- Style.DerivePointerAlignment = true;
-
- verifyFormat("int *a;\n"
- "int *a;\n"
- "int *a;",
- "int *a;\n"
- "int* a;\n"
- "int *a;",
- Style);
- verifyFormat("int* a;\n"
- "int* a;\n"
- "int* a;",
- "int* a;\n"
- "int* a;\n"
- "int *a;",
- Style);
- verifyFormat("int *a;\n"
- "int *a;\n"
- "int *a;",
- "int *a;\n"
- "int * a;\n"
- "int * a;",
- Style);
- verifyFormat("auto x = [] {\n"
- " int *a;\n"
- " int *a;\n"
- " int *a;\n"
- "};",
- "auto x=[]{int *a;\n"
- "int * a;\n"
- "int * a;};",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandsRvalueReferences) {
- verifyFormat("int f(int &&a) {}");
- verifyFormat("int f(int a, char &&b) {}");
- verifyFormat("void f() { int &&a = b; }");
- verifyGoogleFormat("int f(int a, char&& b) {}");
- verifyGoogleFormat("void f() { int&& a = b; }");
-
- verifyIndependentOfContext("A<int &&> a;");
- verifyIndependentOfContext("A<int &&, int &&> a;");
- verifyGoogleFormat("A<int&&> a;");
- verifyGoogleFormat("A<int&&, int&&> a;");
-
- // Not rvalue references:
- verifyFormat("template <bool B, bool C> class A {\n"
- " static_assert(B && C, \"Something is wrong\");\n"
- "};");
- verifyFormat("template <typename T> void swap() noexcept(Bar<T> && Foo<T>);");
- verifyFormat("template <typename T> struct S {\n"
- " explicit(Bar<T> && Foo<T>) S(const S &);\n"
- "};");
- verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
- verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
- verifyFormat("#define A(a, b) (a && b)");
-}
-
-TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
- verifyFormat("void f() {\n"
- " x[aaaaaaaaa -\n"
- " b] = 23;\n"
- "}",
- getLLVMStyleWithColumns(15));
-}
-
-TEST_F(FormatTest, FormatsCasts) {
- verifyFormat("Type *A = static_cast<Type *>(P);");
- verifyFormat("static_cast<Type *>(P);");
- verifyFormat("static_cast<Type &>(Fun)(Args);");
- verifyFormat("static_cast<Type &>(*Fun)(Args);");
- verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;");
- // Check that static_cast<...>(...) does not require the next token to be on
- // the same line.
- verifyFormat("some_loooong_output << something_something__ << "
- "static_cast<const void *>(R)\n"
- " << something;");
- verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
- verifyFormat("const_cast<Type &>(*Fun)(Args);");
- verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
- verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
- verifyFormat("Type *A = (Type *)P;");
- verifyFormat("Type *A = (vector<Type *, int *>)P;");
- verifyFormat("int a = (int)(2.0f);");
- verifyFormat("int a = (int)2.0f;");
- verifyFormat("x[(int32)y];");
- verifyFormat("x = (int32)y;");
- verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
- verifyFormat("int a = (int)*b;");
- verifyFormat("int a = (int)2.0f;");
- verifyFormat("int a = (int)~0;");
- verifyFormat("int a = (int)++a;");
- verifyFormat("int a = (int)sizeof(int);");
- verifyFormat("int a = (int)+2;");
- verifyFormat("my_int a = (my_int)2.0f;");
- verifyFormat("my_int a = (my_int)sizeof(int);");
- verifyFormat("return (my_int)aaa;");
- verifyFormat("throw (my_int)aaa;");
- verifyFormat("#define x ((int)-1)");
- verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
- verifyFormat("#define p(q) ((int *)&q)");
- verifyFormat("fn(a)(b) + 1;");
-
- verifyFormat("void f() { my_int a = (my_int)*b; }");
- verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
- verifyFormat("my_int a = (my_int)~0;");
- verifyFormat("my_int a = (my_int)++a;");
- verifyFormat("my_int a = (my_int)-2;");
- verifyFormat("my_int a = (my_int)1;");
- verifyFormat("my_int a = (my_int *)1;");
- verifyFormat("my_int a = (const my_int)-1;");
- verifyFormat("my_int a = (const my_int *)-1;");
- verifyFormat("my_int a = (my_int)(my_int)-1;");
- verifyFormat("my_int a = (ns::my_int)-2;");
- verifyFormat("case (my_int)ONE:");
- verifyFormat("auto x = (X)this;");
- // Casts in Obj-C style calls used to not be recognized as such.
- verifyGoogleFormat("int a = [(type*)[((type*)val) arg] arg];");
-
- // FIXME: single value wrapped with paren will be treated as cast.
- verifyFormat("void f(int i = (kValue)*kMask) {}");
-
- verifyFormat("{\n"
- " (void)F;\n"
- "}");
-
- // Don't break after a cast's
- verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
- " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
- " bbbbbbbbbbbbbbbbbbbbbb);");
-
- verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
- verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
- verifyFormat("#define CONF_BOOL(x) (bool)(x)");
- verifyFormat("bool *y = (bool *)(void *)(x);");
- verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
- verifyFormat("bool *y = (bool *)(void *)(int)(x);");
- verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
- verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
-
- // These are not casts.
- verifyFormat("void f(int *) {}");
- verifyFormat("f(foo)->b;");
- verifyFormat("f(foo).b;");
- verifyFormat("f(foo)(b);");
- verifyFormat("f(foo)[b];");
- verifyFormat("[](foo) { return 4; }(bar);");
- verifyFormat("(*funptr)(foo)[4];");
- verifyFormat("funptrs[4](foo)[4];");
- verifyFormat("void f(int *);");
- verifyFormat("void f(int *) = 0;");
- verifyFormat("void f(SmallVector<int>) {}");
- verifyFormat("void f(SmallVector<int>);");
- verifyFormat("void f(SmallVector<int>) = 0;");
- verifyFormat("void f(int i = (kA * kB) & kMask) {}");
- verifyFormat("int a = sizeof(int) * b;");
- verifyGoogleFormat("int a = alignof(int) * b;");
- verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
- verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
- verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
-
- // These are not casts, but at some point were confused with casts.
- verifyFormat("virtual void foo(int *) override;");
- verifyFormat("virtual void foo(char &) const;");
- verifyFormat("virtual void foo(int *a, char *) const;");
- verifyFormat("int a = sizeof(int *) + b;");
- verifyGoogleFormat("int a = alignof(int*) + b;");
- verifyFormat("bool b = f(g<int>) && c;");
- verifyFormat("typedef void (*f)(int i) func;");
- verifyFormat("void operator++(int) noexcept;");
- verifyFormat("void operator++(int &) noexcept;");
- verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
- "&) noexcept;");
- verifyFormat(
- "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
- verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
- verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
- verifyFormat("void operator delete(nothrow_t &) noexcept;");
- verifyFormat("void operator delete(foo &) noexcept;");
- verifyFormat("void operator delete(foo) noexcept;");
- verifyFormat("void operator delete(int) noexcept;");
- verifyFormat("void operator delete(int &) noexcept;");
- verifyFormat("void operator delete(int &) volatile noexcept;");
- verifyFormat("void operator delete(int &) const");
- verifyFormat("void operator delete(int &) = default");
- verifyFormat("void operator delete(int &) = delete");
- verifyFormat("void operator delete(int &) [[noreturn]]");
- verifyFormat("void operator delete(int &) throw();");
- verifyFormat("void operator delete(int &) throw(int);");
- verifyFormat("auto operator delete(int &) -> int;");
- verifyFormat("auto operator delete(int &) override");
- verifyFormat("auto operator delete(int &) final");
-
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
- // FIXME: The indentation here is not ideal.
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
- " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
-}
-
-TEST_F(FormatTest, FormatsFunctionTypes) {
- verifyFormat("A<bool()> a;");
- verifyFormat("A<SomeType()> a;");
- verifyFormat("A<void (*)(int, std::string)> a;");
- verifyFormat("A<void *(int)>;");
- verifyFormat("void *(*a)(int *, SomeType *);");
- verifyFormat("int (*func)(void *);");
- verifyFormat("void f() { int (*func)(void *); }");
- verifyFormat("template <class CallbackClass>\n"
- "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
-
- verifyGoogleFormat("A<void*(int*, SomeType*)>;");
- verifyGoogleFormat("void* (*a)(int);");
- verifyGoogleFormat(
- "template <class CallbackClass>\n"
- "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
-
- // Other constructs can look somewhat like function types:
- verifyFormat("A<sizeof(*x)> a;");
- verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
- verifyFormat("some_var = function(*some_pointer_var)[0];");
- verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
- verifyFormat("int x = f(&h)();");
- verifyFormat("returnsFunction(¶m1, ¶m2)(param);");
- verifyFormat("std::function<\n"
- " LooooooooooongTemplatedType<\n"
- " SomeType>*(\n"
- " LooooooooooooooooongType type)>\n"
- " function;",
- getGoogleStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, FormatsPointersToArrayTypes) {
- verifyFormat("A (*foo_)[6];");
- verifyFormat("vector<int> (*foo_)[6];");
-}
-
-TEST_F(FormatTest, BreaksLongVariableDeclarations) {
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " LoooooooooooooooooooooooooooooooooooooooongVariable;");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
- " LoooooooooooooooooooooooooooooooooooooooongVariable;");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " *LoooooooooooooooooooooooooooooooooooooooongVariable;");
-
- // Different ways of ()-initializiation.
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " LoooooooooooooooooooooooooooooooooooooooongVariable({});");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
- " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
-
- // Lambdas should not confuse the variable declaration heuristic.
- verifyFormat("LooooooooooooooooongType\n"
- " variable(nullptr, [](A *a) {});",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, BreaksLongDeclarations) {
- verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
- " AnotherNameForTheLongType;");
- verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
- "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
- "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
- FormatStyle Indented = getLLVMStyle();
- Indented.IndentWrappedFunctionNames = true;
- verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- " LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
- Indented);
- verifyFormat(
- "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
- " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
- Indented);
- verifyFormat(
- "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
- " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
- Indented);
- verifyFormat(
- "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
- " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
- Indented);
-
- // FIXME: Without the comment, this breaks after "(".
- verifyGoogleFormat(
- "LoooooooooooooooooooooooooooooooooooooooongType // break\n"
- " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();");
-
- verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
- " int LoooooooooooooooooooongParam2) {}");
- verifyFormat(
- "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
- " SourceLocation L, IdentifierIn *II,\n"
- " Type *T) {}");
- verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
- "ReallyReaaallyLongFunctionName(\n"
- " const std::string &SomeParameter,\n"
- " const SomeType<string, SomeOtherTemplateParameter>\n"
- " &ReallyReallyLongParameterName,\n"
- " const SomeType<string, SomeOtherTemplateParameter>\n"
- " &AnotherLongParameterName) {}");
- verifyFormat("template <typename A>\n"
- "SomeLoooooooooooooooooooooongType<\n"
- " typename some_namespace::SomeOtherType<A>::Type>\n"
- "Function() {}");
-
- verifyGoogleFormat(
- "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
- " aaaaaaaaaaaaaaaaaaaaaaa;");
- verifyGoogleFormat(
- "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
- " SourceLocation L) {}");
- verifyGoogleFormat(
- "some_namespace::LongReturnType\n"
- "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
- " int first_long_parameter, int second_parameter) {}");
-
- verifyGoogleFormat("template <typename T>\n"
- "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
- "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
- verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int aaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
- " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
-
- verifyFormat("template <typename T> // Templates on own line.\n"
- "static int // Some comment.\n"
- "MyFunction(int a);");
-}
-
-TEST_F(FormatTest, FormatsAccessModifiers) {
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
- FormatStyle::ELBAMS_LogicalBlock);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo { /* comment */\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "private:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- Style);
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "protected:\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo { /* comment */\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "private:\n"
- " int j;\n"
- "};",
- "struct foo { /* comment */\n"
- "\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "\n"
- "private:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- Style);
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo { /* comment */\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "\n"
- "private:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- Style);
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
- verifyNoChange("struct foo {\n"
- "\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- verifyNoChange("struct foo { /* comment */\n"
- "\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "\n"
- "private:\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo { /* comment */\n"
- "private:\n"
- " int i;\n"
- " // comment\n"
- "private:\n"
- " int j;\n"
- "};",
- Style);
- verifyNoChange("struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "#endif\n"
- "private:\n"
- " int i;\n"
- "#ifdef FOO\n"
- "private:\n"
- "#endif\n"
- " int j;\n"
- "};",
- Style);
- Style.AttributeMacros.push_back("FOO");
- Style.AttributeMacros.push_back("BAR");
- verifyFormat("struct foo {\n"
- "FOO private:\n"
- " int i;\n"
- "BAR(x) protected:\n"
- " int j;\n"
- "};",
- Style);
-
- FormatStyle NoEmptyLines = getLLVMStyle();
- NoEmptyLines.MaxEmptyLinesToKeep = 0;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "public:\n"
- "protected:\n"
- " int j;\n"
- "};",
- NoEmptyLines);
-
- NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "private:\n"
- " int i;\n"
- "public:\n"
- "protected:\n"
- " int j;\n"
- "};",
- NoEmptyLines);
-
- NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "public:\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- NoEmptyLines);
-}
-
-TEST_F(FormatTest, FormatsAfterAccessModifiers) {
-
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
-
- // Check if lines are removed.
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n"
- " int j;\n"
- "};",
- Style);
-
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n"
- " int j;\n"
- "};",
- Style);
-
- // Check if lines are added.
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
-
- // Leave tests rely on the code layout, test::messUp can not be used.
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
- Style.MaxEmptyLinesToKeep = 0u;
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
-
- // Check if MaxEmptyLinesToKeep is respected.
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n\n\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n\n\n"
- " int j;\n"
- "};",
- Style);
-
- Style.MaxEmptyLinesToKeep = 1u;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n"
- " int j;\n"
- "};",
- Style);
- // Check if no lines are kept.
- verifyFormat("struct foo {\n"
- "private:\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- " int i;\n"
- "\n"
- "protected:\n"
- " int j;\n"
- "};",
- Style);
- // Check if MaxEmptyLinesToKeep is respected.
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n"
- " int j;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n\n\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n\n\n"
- " int j;\n"
- "};",
- Style);
-
- Style.MaxEmptyLinesToKeep = 10u;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- " void f() {}\n"
- "\n"
- "private:\n"
- "\n\n\n"
- " int i;\n"
- "\n"
- "protected:\n"
- "\n\n\n"
- " int j;\n"
- "};",
- Style);
-
- // Test with comments.
- Style = getLLVMStyle();
- verifyFormat("struct foo {\n"
- "private:\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- " int i;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- "\n"
- " int i;\n"
- "};",
- Style);
-
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- "\n"
- " int i;\n"
- "};",
- "struct foo {\n"
- "private:\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- " // comment\n"
- " void f() {}\n"
- "\n"
- "private: /* comment */\n"
- "\n"
- " int i;\n"
- "};",
- Style);
-
- // Test with preprocessor defines.
- Style = getLLVMStyle();
- verifyFormat("struct foo {\n"
- "private:\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- Style);
- verifyNoChange("struct foo {\n"
- "#ifdef FOO\n"
- "#else\n"
- "private:\n"
- "\n"
- "#endif\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "#else\n"
- "private:\n"
- "\n"
- "#endif\n"
- "};",
- "struct foo {\n"
- "#ifdef FOO\n"
- "#else\n"
- "private:\n"
- "\n"
- "\n"
- "#endif\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#ifdef FOO\n"
- "private:\n"
- "#else\n"
- "#endif\n"
- "};",
- "struct foo {\n"
- "#ifdef FOO\n"
- "private:\n"
- "\n"
- "\n"
- "#else\n"
- "#endif\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "#if 0\n"
- "#else\n"
- "#endif\n"
- "#ifdef FOO\n"
- "private:\n"
- "#endif\n"
- "};",
- "struct foo {\n"
- "#if 0\n"
- "#else\n"
- "#endif\n"
- "#ifdef FOO\n"
- "private:\n"
- "\n"
- "\n"
- "#endif\n"
- "};",
- Style);
-
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- Style);
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- "#ifdef FOO\n"
- "#endif\n"
- " void f() {}\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
- // Combined tests of EmptyLineAfterAccessModifier and
- // EmptyLineBeforeAccessModifier.
- FormatStyle Style = getLLVMStyle();
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "\n"
- "protected:\n"
- "};",
- Style);
-
- Style.MaxEmptyLinesToKeep = 10u;
- // Both remove all new lines.
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- // Leave tests rely on the code layout, test::messUp can not be used.
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
- Style.MaxEmptyLinesToKeep = 10u;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
- Style.MaxEmptyLinesToKeep = 3u;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
- Style.MaxEmptyLinesToKeep = 1u;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style); // Based on new lines in original document and not
- // on the setting.
-
- Style.MaxEmptyLinesToKeep = 10u;
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
- // Newlines are kept if they are greater than zero,
- // test::messUp removes all new lines which changes the logic
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- // test::messUp removes all new lines which changes the logic
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style); // test::messUp removes all new lines which changes
- // the logic.
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
- verifyNoChange("struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style); // test::messUp removes all new lines which changes
- // the logic.
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-
- Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
- Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
- verifyFormat("struct foo {\n"
- "private:\n"
- "protected:\n"
- "};",
- "struct foo {\n"
- "private:\n"
- "\n\n\n"
- "protected:\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, FormatsArrays) {
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
- " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
- " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
- verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
- " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
- " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
- verifyFormat(
- "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
- " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
- " .aaaaaaaaaaaaaaaaaaaaaa();");
-
- verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
- verifyFormat(
- "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
- " .aaaaaaa[0]\n"
- " .aaaaaaaaaaaaaaaaaaaaaa();");
- verifyFormat("a[::b::c];");
-
- verifyFormat("{\n"
- " (*a)[0] = 1;\n"
- "}");
-
- verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
-
- FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
- verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
-}
-
-TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
- verifyFormat("(a)->b();");
- verifyFormat("--a;");
-}
-
-TEST_F(FormatTest, HandlesIncludeDirectives) {
- verifyFormat("#include <string>\n"
- "#include <a/b/c.h>\n"
- "#include \"a/b/string\"\n"
- "#include \"string.h\"\n"
- "#include \"string.h\"\n"
- "#include <a-a>\n"
- "#include < path with space >\n"
- "#include_next <test.h>"
- "#include \"abc.h\" // this is included for ABC\n"
- "#include \"some long include\" // with a comment\n"
- "#include \"some very long include path\"\n"
- "#include <some/very/long/include/path>",
- getLLVMStyleWithColumns(35));
- verifyFormat("#include \"a.h\"", "#include \"a.h\"");
- verifyFormat("#include <a>", "#include<a>");
-
- verifyFormat("#import <string>");
- verifyFormat("#import <a/b/c.h>");
- verifyFormat("#import \"a/b/string\"");
- verifyFormat("#import \"string.h\"");
- verifyFormat("#import \"string.h\"");
- verifyFormat("#if __has_include(<strstream>)\n"
- "#include <strstream>\n"
- "#endif");
-
- verifyFormat("#define MY_IMPORT <a/b>");
-
- verifyFormat("#if __has_include(<a/b>)");
- verifyFormat("#if __has_include_next(<a/b>)");
- verifyFormat("#define F __has_include(<a/b>)");
- verifyFormat("#define F __has_include_next(<a/b>)");
-
- // Protocol buffer definition or missing "#".
- verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
- getLLVMStyleWithColumns(30));
-
- FormatStyle Style = getLLVMStyle();
- Style.AlwaysBreakBeforeMultilineStrings = true;
- Style.ColumnLimit = 0;
- verifyFormat("#import \"abc.h\"", Style);
-
- // But 'import' might also be a regular C++ namespace.
- verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
- verifyFormat("import::Bar foo(val ? 2 : 1);");
-}
-
-//===----------------------------------------------------------------------===//
-// Error recovery tests.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, IncompleteParameterLists) {
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
- " double *min_x,\n"
- " double *max_x,\n"
- " double *min_y,\n"
- " double *max_y,\n"
- " double *min_z,\n"
- " double *max_z, ) {}",
- NoBinPacking);
-}
-
-TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
- verifyFormat("void f() { return; }\n42");
- verifyFormat("void f() {\n"
- " if (0)\n"
- " return;\n"
- "}\n"
- "42");
- verifyFormat("void f() { return }\n42");
- verifyFormat("void f() {\n"
- " if (0)\n"
- " return\n"
- "}\n"
- "42");
-}
-
-TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
- verifyFormat("void f() { return }", "void f ( ) { return }");
- verifyFormat("void f() {\n"
- " if (a)\n"
- " return\n"
- "}",
- "void f ( ) { if ( a ) return }");
- verifyFormat("namespace N {\n"
- "void f()\n"
- "}",
- "namespace N { void f() }");
- verifyFormat("namespace N {\n"
- "void f() {}\n"
- "void g()\n"
- "} // namespace N",
- "namespace N { void f( ) { } void g( ) }");
-}
-
-TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
- verifyFormat("int aaaaaaaa =\n"
- " // Overlylongcomment\n"
- " b;",
- getLLVMStyleWithColumns(20));
- verifyFormat("function(\n"
- " ShortArgument,\n"
- " LoooooooooooongArgument);",
- getLLVMStyleWithColumns(20));
-}
-
-TEST_F(FormatTest, IncorrectAccessSpecifier) {
- verifyFormat("public:");
- verifyFormat("class A {\n"
- "public\n"
- " void f() {}\n"
- "};");
- verifyFormat("public\n"
- "int qwerty;");
- verifyFormat("public\n"
- "B {}");
- verifyFormat("public\n"
- "{\n"
- "}");
- verifyFormat("public\n"
- "B { int x; }");
-}
-
-TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
- verifyFormat("{");
- verifyFormat("#})");
- verifyNoCrash("(/**/[:!] ?[).");
- verifyNoCrash("struct X {\n"
- " operator iunt(\n"
- "};");
- verifyNoCrash("struct Foo {\n"
- " operator foo(bar\n"
- "};");
- verifyNoCrash("decltype( {\n"
- " {");
-}
-
-TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
- // Found by oss-fuzz:
- // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
- FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
- Style.ColumnLimit = 60;
- verifyNoCrash(
- "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
- "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
- "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
- Style);
-}
-
-TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
- verifyFormat("do {\n}");
- verifyFormat("do {\n}\n"
- "f();");
- verifyFormat("do {\n}\n"
- "wheeee(fun);");
- verifyFormat("do {\n"
- " f();\n"
- "}");
-}
-
-TEST_F(FormatTest, IncorrectCodeMissingParens) {
- verifyFormat("if {\n foo;\n foo();\n}");
- verifyFormat("switch {\n foo;\n foo();\n}");
- verifyIncompleteFormat("for {\n foo;\n foo();\n}");
- verifyIncompleteFormat("ERROR: for target;");
- verifyFormat("while {\n foo;\n foo();\n}");
- verifyFormat("do {\n foo;\n foo();\n} while;");
-}
-
-TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
- verifyIncompleteFormat("namespace {\n"
- "class Foo { Foo (\n"
- "};\n"
- "} // namespace");
-}
-
-TEST_F(FormatTest, IncorrectCodeErrorDetection) {
- verifyFormat("{\n"
- " {\n"
- " }",
- "{\n"
- "{\n"
- "}");
- verifyFormat("{\n"
- " {\n"
- " }",
- "{\n"
- " {\n"
- "}");
- verifyFormat("{\n"
- " {\n"
- " }");
- verifyFormat("{\n"
- " {\n"
- " }\n"
- "}\n"
- "}",
- "{\n"
- " {\n"
- " }\n"
- " }\n"
- "}");
-
- verifyFormat("{\n"
- " {\n"
- " breakme(\n"
- " qwe);\n"
- " }",
- "{\n"
- " {\n"
- " breakme(qwe);\n"
- "}",
- getLLVMStyleWithColumns(10));
-}
-
-TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
- verifyFormat("int x = {\n"
- " avariable,\n"
- " b(alongervariable)};",
- getLLVMStyleWithColumns(25));
-}
-
-TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
- verifyFormat("return (a)(b){1, 2, 3};");
-}
-
-TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
- verifyFormat("vector<int> x{1, 2, 3, 4};");
- verifyFormat("vector<int> x{\n"
- " 1,\n"
- " 2,\n"
- " 3,\n"
- " 4,\n"
- "};");
- verifyFormat("vector<T> x{{}, {}, {}, {}};");
- verifyFormat("f({1, 2});");
- verifyFormat("auto v = Foo{-1};");
- verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
- verifyFormat("Class::Class : member{1, 2, 3} {}");
- verifyFormat("new vector<int>{1, 2, 3};");
- verifyFormat("new int[3]{1, 2, 3};");
- verifyFormat("new int{1};");
- verifyFormat("return {arg1, arg2};");
- verifyFormat("return {arg1, SomeType{parameter}};");
- verifyFormat("int count = set<int>{f(), g(), h()}.size();");
- verifyFormat("new T{arg1, arg2};");
- verifyFormat("f(MyMap[{composite, key}]);");
- verifyFormat("class Class {\n"
- " T member = {arg1, arg2};\n"
- "};");
- verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
- verifyFormat("const struct A a = {.a = 1, .b = 2};");
- verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
- verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
- verifyFormat("int a = std::is_integral<int>{} + 0;");
-
- verifyFormat("int foo(int i) { return fo1{}(i); }");
- verifyFormat("int foo(int i) { return fo1{}(i); }");
- verifyFormat("auto i = decltype(x){};");
- verifyFormat("auto i = typeof(x){};");
- verifyFormat("auto i = _Atomic(x){};");
- verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
- verifyFormat("Node n{1, Node{1000}, //\n"
- " 2};");
- verifyFormat("Aaaa aaaaaaa{\n"
- " {\n"
- " aaaa,\n"
- " },\n"
- "};");
- verifyFormat("class C : public D {\n"
- " SomeClass SC{2};\n"
- "};");
- verifyFormat("class C : public A {\n"
- " class D : public B {\n"
- " void f() { int i{2}; }\n"
- " };\n"
- "};");
- verifyFormat("#define A {a, a},");
- // Don't confuse braced list initializers with compound statements.
- verifyFormat(
- "class A {\n"
- " A() : a{} {}\n"
- " A() : Base<int>{} {}\n"
- " A() : Base<Foo<int>>{} {}\n"
- " A(int b) : b(b) {}\n"
- " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
- " int a, b;\n"
- " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
- " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
- "{}\n"
- "};");
-
- // Avoid breaking between equal sign and opening brace
- FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
- AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
- verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
- " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
- " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
- " {\"ccccccccccccccccccccc\", 2}};",
- AvoidBreakingFirstArgument);
-
- // Binpacking only if there is no trailing comma
- verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
- " cccccccccc, dddddddddd};",
- getLLVMStyleWithColumns(50));
- verifyFormat("const Aaaaaa aaaaa = {\n"
- " aaaaaaaaaaa,\n"
- " bbbbbbbbbbb,\n"
- " ccccccccccc,\n"
- " ddddddddddd,\n"
- "};",
- getLLVMStyleWithColumns(50));
-
- // Cases where distinguising braced lists and blocks is hard.
- verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
- verifyFormat("void f() {\n"
- " return; // comment\n"
- "}\n"
- "SomeType t;");
- verifyFormat("void f() {\n"
- " if (a) {\n"
- " f();\n"
- " }\n"
- "}\n"
- "SomeType t;");
-
- // In combination with BinPackArguments = false.
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackArguments = false;
- verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- " iiiiii,\n"
- " jjjjjj,\n"
- " kkkkkk};",
- NoBinPacking);
- verifyFormat("const Aaaaaa aaaaa = {\n"
- " aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- " iiiiii,\n"
- " jjjjjj,\n"
- " kkkkkk,\n"
- "};",
- NoBinPacking);
- verifyFormat(
- "const Aaaaaa aaaaa = {\n"
- " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n"
- " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n"
- " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
- "};",
- NoBinPacking);
-
- NoBinPacking.BinPackLongBracedList = false;
- verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- " iiiiii,\n"
- " jjjjjj,\n"
- " kkkkkk,\n"
- " aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- " iiiiii};",
- NoBinPacking);
- verifyFormat("const Aaaaaa aaaaa = {\n"
- " aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- " iiiiii,\n"
- " jjjjjj,\n"
- " kkkkkk,\n"
- " aaaaa,\n"
- " bbbbb,\n"
- " ccccc,\n"
- " ddddd,\n"
- " eeeee,\n"
- " ffffff,\n"
- " ggggg,\n"
- " hhhhhh,\n"
- "};",
- NoBinPacking);
-
- NoBinPacking.BreakAfterOpenBracketBracedList = true;
- verifyFormat("static uint8 CddDp83848Reg[] = {\n"
- " CDDDP83848_BMCR_REGISTER,\n"
- " CDDDP83848_BMSR_REGISTER,\n"
- " CDDDP83848_RBR_REGISTER};",
- "static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
- " CDDDP83848_BMSR_REGISTER,\n"
- " CDDDP83848_RBR_REGISTER};",
- NoBinPacking);
-
- // FIXME: The alignment of these trailing comments might be bad. Then again,
- // this might be utterly useless in real code.
- verifyFormat("Constructor::Constructor()\n"
- " : some_value{ //\n"
- " aaaaaaa, //\n"
- " bbbbbbb} {}");
-
- // In braced lists, the first comment is always assumed to belong to the
- // first element. Thus, it can be moved to the next or previous line as
- // appropriate.
- verifyFormat("function({// First element:\n"
- " 1,\n"
- " // Second element:\n"
- " 2});",
- "function({\n"
- " // First element:\n"
- " 1,\n"
- " // Second element:\n"
- " 2});");
- verifyFormat("std::vector<int> MyNumbers{\n"
- " // First element:\n"
- " 1,\n"
- " // Second element:\n"
- " 2};",
- "std::vector<int> MyNumbers{// First element:\n"
- " 1,\n"
- " // Second element:\n"
- " 2};",
- getLLVMStyleWithColumns(30));
- // A trailing comma should still lead to an enforced line break and no
- // binpacking.
- verifyFormat("vector<int> SomeVector = {\n"
- " // aaa\n"
- " 1,\n"
- " 2,\n"
- "};",
- "vector<int> SomeVector = { // aaa\n"
- " 1, 2, };");
-
- // C++11 brace initializer list l-braces should not be treated any differently
- // when breaking before lambda bodies is enabled
- FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
- BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
- BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
- BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
- verifyFormat(
- "std::runtime_error{\n"
- " \"Long string which will force a break onto the next line...\"};",
- BreakBeforeLambdaBody);
-
- FormatStyle ExtraSpaces = getLLVMStyle();
- ExtraSpaces.Cpp11BracedListStyle = FormatStyle::BLS_Block;
- ExtraSpaces.ColumnLimit = 75;
- verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
- verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
- verifyFormat("f({ 1, 2 });", ExtraSpaces);
- verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
- verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
- verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
- verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
- verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
- verifyFormat("return { arg1, arg2 };", ExtraSpaces);
- verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
- verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
- verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
- verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
- verifyFormat("class Class {\n"
- " T member = { arg1, arg2 };\n"
- "};",
- ExtraSpaces);
- verifyFormat(
- "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
- " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
- " bbbbbbbbbbbbbbbbbbbb, bbbbb };",
- ExtraSpaces);
- verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
- verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
- ExtraSpaces);
- verifyFormat(
- "someFunction(OtherParam,\n"
- " BracedList{ // comment 1 (Forcing interesting break)\n"
- " param1, param2,\n"
- " // comment 2\n"
- " param3, param4 });",
- ExtraSpaces);
- verifyFormat(
- "std::this_thread::sleep_for(\n"
- " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
- ExtraSpaces);
- verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
- " aaaaaaa,\n"
- " aaaaaaaaaa,\n"
- " aaaaa,\n"
- " aaaaaaaaaaaaaaa,\n"
- " aaa,\n"
- " aaaaaaaaaa,\n"
- " a,\n"
- " aaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaa,\n"
- " a};");
- verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
- verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
- verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
-
- // Avoid breaking between initializer/equal sign and opening brace
- ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
- verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
- " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
- " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
- " { \"ccccccccccccccccccccc\", 2 }\n"
- "};",
- ExtraSpaces);
- verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
- " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
- " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
- " { \"ccccccccccccccccccccc\", 2 }\n"
- "};",
- ExtraSpaces);
-
- FormatStyle SpaceBeforeBrace = getLLVMStyle();
- SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
- verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
- verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
-
- FormatStyle SpaceBetweenBraces = getLLVMStyle();
- SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
- SpaceBetweenBraces.SpacesInParens = FormatStyle::SIPO_Custom;
- SpaceBetweenBraces.SpacesInParensOptions.Other = true;
- SpaceBetweenBraces.SpacesInSquareBrackets = true;
- verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
- verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
- verifyFormat("vector< int > x{ // comment 1\n"
- " 1, 2, 3, 4 };",
- SpaceBetweenBraces);
- SpaceBetweenBraces.ColumnLimit = 20;
- verifyFormat("vector< int > x{\n"
- " 1, 2, 3, 4 };",
- "vector<int>x{1,2,3,4};", SpaceBetweenBraces);
- SpaceBetweenBraces.ColumnLimit = 24;
- verifyFormat("vector< int > x{ 1, 2,\n"
- " 3, 4 };",
- "vector<int>x{1,2,3,4};", SpaceBetweenBraces);
- verifyFormat("vector< int > x{\n"
- " 1,\n"
- " 2,\n"
- " 3,\n"
- " 4,\n"
- "};",
- "vector<int>x{1,2,3,4,};", SpaceBetweenBraces);
- verifyFormat("vector< int > x{};", SpaceBetweenBraces);
- SpaceBetweenBraces.SpacesInParens = FormatStyle::SIPO_Custom;
- SpaceBetweenBraces.SpacesInParensOptions.InEmptyParentheses = true;
- verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
-}
-
-TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
- verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777};");
- verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, //\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777};");
- verifyFormat(
- "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, // comment\n"
- " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
- " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
- " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
- " 7777777};");
- verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
- " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
- " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
- verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
- " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
- " // Separating comment.\n"
- " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
- verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
- " // Leading comment\n"
- " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
- " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
- verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
- " 1, 1, 1, 1};",
- getLLVMStyleWithColumns(39));
- verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
- " 1, 1, 1, 1};",
- getLLVMStyleWithColumns(38));
- verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
- " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
- getLLVMStyleWithColumns(43));
- verifyFormat(
- "static unsigned SomeValues[10][3] = {\n"
- " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n"
- " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
- verifyFormat("static auto fields = new vector<string>{\n"
- " \"aaaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaa\",\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
- "};");
- verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
- verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
- " 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
- " 3, cccccccccccccccccccccc};",
- getLLVMStyleWithColumns(60));
-
- // Trailing commas.
- verifyFormat("vector<int> x = {\n"
- " 1, 1, 1, 1, 1, 1, 1, 1,\n"
- "};",
- getLLVMStyleWithColumns(39));
- verifyFormat("vector<int> x = {\n"
- " 1, 1, 1, 1, 1, 1, 1, 1, //\n"
- "};",
- getLLVMStyleWithColumns(39));
- verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
- " 1, 1, 1, 1,\n"
- " /**/ /**/};",
- getLLVMStyleWithColumns(39));
-
- // Trailing comment in the first line.
- verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n"
- " 1111111111, 2222222222, 33333333333, 4444444444, //\n"
- " 111111111, 222222222, 3333333333, 444444444, //\n"
- " 11111111, 22222222, 333333333, 44444444};");
- // Trailing comment in the last line.
- verifyFormat("int aaaaa[] = {\n"
- " 1, 2, 3, // comment\n"
- " 4, 5, 6 // comment\n"
- "};");
-
- // With nested lists, we should either format one item per line or all nested
- // lists one on line.
- // FIXME: For some nested lists, we can do better.
- verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
- " {aaaaaaaaaaaaaaaaaaa},\n"
- " {aaaaaaaaaaaaaaaaaaaaa},\n"
- " {aaaaaaaaaaaaaaaaa}};",
- getLLVMStyleWithColumns(60));
- verifyFormat(
- "SomeStruct my_struct_array = {\n"
- " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
- " aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
- " {aaa, aaa},\n"
- " {aaa, aaa},\n"
- " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
- " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
-
- // No column layout should be used here.
- verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
-
- verifyNoCrash("a<,");
-
- // No braced initializer here.
- verifyFormat("void f() {\n"
- " struct Dummy {};\n"
- " f(v);\n"
- "}");
- verifyFormat("void foo() {\n"
- " { // asdf\n"
- " {\n"
- " int a;\n"
- " }\n"
- " }\n"
- " {\n"
- " {\n"
- " int b;\n"
- " }\n"
- " }\n"
- "}");
- verifyFormat("namespace n {\n"
- "void foo() {\n"
- " {\n"
- " {\n"
- " statement();\n"
- " if (false) {\n"
- " }\n"
- " }\n"
- " }\n"
- " {\n"
- " }\n"
- "}\n"
- "} // namespace n");
-
- // Long lists should be formatted in columns even if they are nested.
- verifyFormat(
- "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
- " 1, 22, 333, 4444, 55555, 666666, 7777777});");
-
- // Allow "single-column" layout even if that violates the column limit. There
- // isn't going to be a better way.
- verifyFormat("std::vector<int> a = {\n"
- " aaaaaaaa,\n"
- " aaaaaaaa,\n"
- " aaaaaaaa,\n"
- " aaaaaaaa,\n"
- " aaaaaaaaaa,\n"
- " aaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
- getLLVMStyleWithColumns(30));
- verifyFormat("vector<int> aaaa = {\n"
- " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaa.aaaaaaa,\n"
- " aaaaaa.aaaaaaa,\n"
- " aaaaaa.aaaaaaa,\n"
- " aaaaaa.aaaaaaa,\n"
- "};");
-
- // Don't create hanging lists.
- verifyFormat("someFunction(Param, {List1, List2,\n"
- " List3});",
- getLLVMStyleWithColumns(35));
- verifyFormat("someFunction(Param, Param,\n"
- " {List1, List2,\n"
- " List3});",
- getLLVMStyleWithColumns(35));
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
- " aaaaaaaaaaaaaaaaaaaaaaa);");
-
- // No possible column formats, don't want the optimal paths penalized.
- verifyFormat(
- "waarudo::unit desk = {\n"
- " .s = \"desk\", .p = p, .b = [] { return w::r{3, 10} * w::m; }};");
- verifyFormat("SomeType something1([](const Input &i) -> Output { return "
- "Output{1, 2}; },\n"
- " [](const Input &i) -> Output { return "
- "Output{1, 2}; });");
- FormatStyle NoBinPacking = getLLVMStyle();
- NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("waarudo::unit desk = {\n"
- " .s = \"desk\", .p = p, .b = [] { return w::r{3, 10, 1, 1, "
- "1, 1} * w::m; }};",
- NoBinPacking);
-}
-
-TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
- FormatStyle DoNotMerge = getLLVMStyle();
- DoNotMerge.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle();
-
- verifyFormat("void f() { return 42; }");
- verifyFormat("void f() {\n"
- " return 42;\n"
- "}",
- DoNotMerge);
- verifyFormat("void f() {\n"
- " // Comment\n"
- "}");
- verifyFormat("{\n"
- "#error {\n"
- " int a;\n"
- "}");
- verifyFormat("{\n"
- " int a;\n"
- "#error {\n"
- "}");
- verifyFormat("void f() {} // comment");
- verifyFormat("void f() { int a; } // comment");
- verifyFormat("void f() {\n"
- "} // comment",
- DoNotMerge);
- verifyFormat("void f() {\n"
- " int a;\n"
- "} // comment",
- DoNotMerge);
- verifyFormat("void f() {\n"
- "} // comment",
- getLLVMStyleWithColumns(15));
-
- verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
- verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22));
-
- verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
- verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
- verifyGoogleFormat("class C {\n"
- " C()\n"
- " : iiiiiiii(nullptr),\n"
- " kkkkkkk(nullptr),\n"
- " mmmmmmm(nullptr),\n"
- " nnnnnnn(nullptr) {}\n"
- "};");
-
- FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
- verifyFormat("A() : b(0) {}", "A():b(0){}", NoColumnLimit);
- verifyFormat("class C {\n"
- " A() : b(0) {}\n"
- "};",
- "class C{A():b(0){}};", NoColumnLimit);
- verifyFormat("A()\n"
- " : b(0) {\n"
- "}",
- "A()\n:b(0)\n{\n}", NoColumnLimit);
-
- FormatStyle NoColumnLimitWrapAfterFunction = NoColumnLimit;
- NoColumnLimitWrapAfterFunction.BreakBeforeBraces = FormatStyle::BS_Custom;
- NoColumnLimitWrapAfterFunction.BraceWrapping.AfterFunction = true;
- verifyFormat("class C {\n"
- "#pragma foo\n"
- " int foo { return 0; }\n"
- "};",
- NoColumnLimitWrapAfterFunction);
- verifyFormat("class C {\n"
- "#pragma foo\n"
- " void foo {}\n"
- "};",
- NoColumnLimitWrapAfterFunction);
-
- FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
- DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle();
- verifyFormat("A() : b(0) {\n"
- "}",
- DoNotMergeNoColumnLimit);
- verifyNoChange("A()\n"
- " : b(0) {\n"
- "}",
- DoNotMergeNoColumnLimit);
- verifyFormat("A()\n"
- " : b(0) {\n"
- "}",
- "A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit);
-
- verifyFormat("#define A \\\n"
- " void f() { \\\n"
- " int i; \\\n"
- " }",
- getLLVMStyleWithColumns(20));
- verifyFormat("#define A \\\n"
- " void f() { int i; }",
- getLLVMStyleWithColumns(21));
- verifyFormat("#define A \\\n"
- " void f() { \\\n"
- " int i; \\\n"
- " } \\\n"
- " int j;",
- getLLVMStyleWithColumns(22));
- verifyFormat("#define A \\\n"
- " void f() { int i; } \\\n"
- " int j;",
- getLLVMStyleWithColumns(23));
-
- verifyFormat(
- "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {}");
-
- constexpr StringRef Code("void foo() { /* Empty */ }");
- verifyFormat(Code);
- verifyFormat(Code, "void foo() { /* Empty */\n"
- "}");
- verifyFormat(Code, "void foo() {\n"
- "/* Empty */\n"
- "}");
-}
-
-TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
- FormatStyle MergeEmptyOnly = getLLVMStyle();
- MergeEmptyOnly.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeEmptyOnly);
- verifyFormat("class C {\n"
- " int f() {\n"
- " return 42;\n"
- " }\n"
- "};",
- MergeEmptyOnly);
- verifyFormat("int f() {}", MergeEmptyOnly);
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- MergeEmptyOnly);
-
- // Also verify behavior when BraceWrapping.AfterFunction = true
- MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
- MergeEmptyOnly.BraceWrapping.AfterFunction = true;
- verifyFormat("int f() {}", MergeEmptyOnly);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeEmptyOnly);
-}
-
-TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
- FormatStyle MergeInlineOnly = getLLVMStyle();
- MergeInlineOnly.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- MergeInlineOnly);
-
- // SFS_Inline implies SFS_Empty
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f() {}", MergeInlineOnly);
- // https://llvm.org/PR54147
- verifyFormat("auto lambda = []() {\n"
- " // comment\n"
- " f();\n"
- " g();\n"
- "};",
- MergeInlineOnly);
-
- verifyFormat("class C {\n"
- "#ifdef A\n"
- " int f() { return 42; }\n"
- "#endif\n"
- "};",
- MergeInlineOnly);
-
- verifyFormat("struct S {\n"
- "// comment\n"
- "#ifdef FOO\n"
- " int foo() { bar(); }\n"
- "#endif\n"
- "};",
- MergeInlineOnly);
-
- MergeInlineOnly.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- verifyFormat("#define Foo \\\n"
- " struct S { \\\n"
- " void foo() { return; } \\\n"
- " }",
- MergeInlineOnly);
-
- // Also verify behavior when BraceWrapping.AfterFunction = true
- MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
- MergeInlineOnly.BraceWrapping.AfterFunction = true;
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f()\n"
- "{\n"
- " return 42;\n"
- "}",
- MergeInlineOnly);
-
- // SFS_Inline implies SFS_Empty
- verifyFormat("int f() {}", MergeInlineOnly);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeInlineOnly);
-
- MergeInlineOnly.BraceWrapping.AfterClass = true;
- MergeInlineOnly.BraceWrapping.AfterStruct = true;
- verifyFormat("class C\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("struct C\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f()\n"
- "{\n"
- " return 42;\n"
- "}",
- MergeInlineOnly);
- verifyFormat("int f() {}", MergeInlineOnly);
- verifyFormat("class C\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("struct C\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("struct C\n"
- "// comment\n"
- "/* comment */\n"
- "// comment\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("/* comment */ struct C\n"
- "{\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
-}
-
-TEST_F(FormatTest, CustomShortFunctionOptions) {
- FormatStyle CustomEmpty = getLLVMStyle();
- CustomEmpty.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
-
- // Empty functions should be on a single line
- verifyFormat("int f() {}", CustomEmpty);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- CustomEmpty);
-
- // Non-empty functions should be multi-line
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- CustomEmpty);
- verifyFormat("class C {\n"
- " int f() {\n"
- " return 42;\n"
- " }\n"
- "};",
- CustomEmpty);
-
- // test with comment
- verifyFormat("void f3() { /* comment */ }", CustomEmpty);
-
- // Test with AfterFunction = true
- CustomEmpty.BreakBeforeBraces = FormatStyle::BS_Custom;
- CustomEmpty.BraceWrapping.AfterFunction = true;
- verifyFormat("int f() {}", CustomEmpty);
- verifyFormat("int g()\n"
- "{\n"
- " return 42;\n"
- "}",
- CustomEmpty);
-
- // Test with Inline = true, All = false
- FormatStyle CustomInline = getLLVMStyle();
- CustomInline.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setInlineOnly();
-
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- CustomInline);
-
- // Non-empty inline functions should be single-line
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- CustomInline);
-
- // Non-inline functions should be multi-line
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- CustomInline);
- verifyFormat("int g() {\n"
- "}",
- CustomInline);
-
- // Test with All = true
- FormatStyle CustomAll = getLLVMStyle();
- CustomAll.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
-
- // All functions should be on a single line if they fit
- verifyFormat("int f() { return 42; }", CustomAll);
- verifyFormat("int g() { return f() + h(); }", CustomAll);
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- CustomAll);
-
- verifyFormat("int f() {}", CustomAll);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- CustomAll);
-
- // Test various combinations
- FormatStyle CustomMixed = getLLVMStyle();
- CustomMixed.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
-
- // Empty functions should be on a single line
- verifyFormat("int f() {}", CustomMixed);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- CustomMixed);
-
- // Inline non-empty functions should be on a single line
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- CustomMixed);
-
- // Non-inline non-empty functions should be multi-line
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- CustomMixed);
-}
-
-TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
- FormatStyle MergeInlineOnly = getLLVMStyle();
- MergeInlineOnly.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setInlineOnly();
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f() {\n"
- " return 42;\n"
- "}",
- MergeInlineOnly);
-
- // SFS_InlineOnly does not imply SFS_Empty
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f() {\n"
- "}",
- MergeInlineOnly);
-
- MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
- verifyFormat("class Foo\n"
- " {\n"
- " void f() { foo(); }\n"
- " };",
- MergeInlineOnly);
-
- // Also verify behavior when BraceWrapping.AfterFunction = true
- MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
- MergeInlineOnly.BraceWrapping.AfterFunction = true;
- verifyFormat("class C {\n"
- " int f() { return 42; }\n"
- "};",
- MergeInlineOnly);
- verifyFormat("int f()\n"
- "{\n"
- " return 42;\n"
- "}",
- MergeInlineOnly);
-
- // SFS_InlineOnly does not imply SFS_Empty
- verifyFormat("int f()\n"
- "{\n"
- "}",
- MergeInlineOnly);
- verifyFormat("class C {\n"
- " int f() {}\n"
- "};",
- MergeInlineOnly);
-}
-
-TEST_F(FormatTest, SplitEmptyFunction) {
- FormatStyle Style = getLLVMStyleWithColumns(40);
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- Style.BraceWrapping.SplitEmptyFunction = false;
-
- verifyFormat("int f()\n"
- "{}",
- Style);
- verifyFormat("int f()\n"
- "{\n"
- " return 42;\n"
- "}",
- Style);
- verifyFormat("int f()\n"
- "{\n"
- " // some comment\n"
- "}",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- verifyFormat("int f() {}", Style);
- verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
- "{}",
- Style);
- verifyFormat("int f()\n"
- "{\n"
- " return 0;\n"
- "}",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyAndInline();
- verifyFormat("class Foo {\n"
- " int f() {}\n"
- "};",
- Style);
- verifyFormat("class Foo {\n"
- " int f() { return 0; }\n"
- "};",
- Style);
- verifyFormat("class Foo {\n"
- " int f() { return 0; }\n"
- "};",
- Style);
- verifyFormat("class Foo {\n"
- " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
- " {}\n"
- "};",
- Style);
- verifyFormat("class Foo {\n"
- " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
- " {\n"
- " return 0;\n"
- " }\n"
- "};",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- verifyFormat("int f() {}", Style);
- verifyFormat("int f() { return 0; }", Style);
- verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
- "{}",
- Style);
- verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
- "{\n"
- " return 0;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
- FormatStyle Style = getLLVMStyleWithColumns(40);
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
- Style.BraceWrapping.SplitEmptyFunction = true;
- Style.BraceWrapping.SplitEmptyRecord = false;
-
- verifyFormat("class C {};", Style);
- verifyFormat("struct C {};", Style);
- verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
- "{\n"
- "}",
- Style);
- verifyFormat("class C {\n"
- " C()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
- " bbbbbbbbbbbbbbbbbbb()\n"
- " {\n"
- " }\n"
- " void\n"
- " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
- " {\n"
- " }\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, MergeShortFunctionBody) {
- auto Style = getLLVMStyle();
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterFunction = true;
-
- verifyFormat("int foo()\n"
- "{ return 1; }",
- Style);
-}
-
-TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
- FormatStyle Style = getLLVMStyle();
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- verifyFormat("#ifdef A\n"
- "int f() {}\n"
- "#else\n"
- "int g() {}\n"
- "#endif",
- Style);
-}
-
-TEST_F(FormatTest, SplitEmptyClass) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- Style.BraceWrapping.SplitEmptyRecord = false;
-
- verifyFormat("class Foo\n"
- "{};",
- Style);
- verifyFormat("/* something */ class Foo\n"
- "{};",
- Style);
- verifyFormat("template <typename X> class Foo\n"
- "{};",
- Style);
- verifyFormat("class Foo\n"
- "{\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef class Foo\n"
- "{\n"
- "} Foo_t;",
- Style);
-
- Style.BraceWrapping.SplitEmptyRecord = true;
- Style.BraceWrapping.AfterStruct = true;
- verifyFormat("class rep\n"
- "{\n"
- "};",
- Style);
- verifyFormat("struct rep\n"
- "{\n"
- "};",
- Style);
- verifyFormat("template <typename T> class rep\n"
- "{\n"
- "};",
- Style);
- verifyFormat("template <typename T> struct rep\n"
- "{\n"
- "};",
- Style);
- verifyFormat("class rep\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("struct rep\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("template <typename T> class rep\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("template <typename T> struct rep\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("template <typename T> class rep // Foo\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("template <typename T> struct rep // Bar\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
-
- verifyFormat("template <typename T> class rep<T>\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
-
- verifyFormat("template <typename T> class rep<std::complex<T>>\n"
- "{\n"
- " int x;\n"
- "};",
- Style);
- verifyFormat("template <typename T> class rep<std::complex<T>>\n"
- "{\n"
- "};",
- Style);
-
- verifyFormat("#include \"stdint.h\"\n"
- "namespace rep {}",
- Style);
- verifyFormat("#include <stdint.h>\n"
- "namespace rep {}",
- Style);
- verifyFormat("#include <stdint.h>\n"
- "namespace rep {}",
- "#include <stdint.h>\n"
- "namespace rep {\n"
- "\n"
- "\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, SplitEmptyStruct) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterStruct = true;
- Style.BraceWrapping.SplitEmptyRecord = false;
-
- verifyFormat("struct Foo\n"
- "{};",
- Style);
- verifyFormat("/* something */ struct Foo\n"
- "{};",
- Style);
- verifyFormat("template <typename X> struct Foo\n"
- "{};",
- Style);
- verifyFormat("struct Foo\n"
- "{\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef struct Foo\n"
- "{\n"
- "} Foo_t;",
- Style);
- // typedef struct Bar {} Bar_t;
-}
-
-TEST_F(FormatTest, SplitEmptyUnion) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterUnion = true;
- Style.BraceWrapping.SplitEmptyRecord = false;
-
- verifyFormat("union Foo\n"
- "{};",
- Style);
- verifyFormat("/* something */ union Foo\n"
- "{};",
- Style);
- verifyFormat("union Foo\n"
- "{\n"
- " A,\n"
- "};",
- Style);
- verifyFormat("typedef union Foo\n"
- "{\n"
- "} Foo_t;",
- Style);
-}
-
-TEST_F(FormatTest, SplitEmptyNamespace) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterNamespace = true;
- Style.BraceWrapping.SplitEmptyNamespace = false;
-
- verifyFormat("namespace Foo\n"
- "{};",
- Style);
- verifyFormat("/* something */ namespace Foo\n"
- "{};",
- Style);
- verifyFormat("inline namespace Foo\n"
- "{};",
- Style);
- verifyFormat("/* something */ inline namespace Foo\n"
- "{};",
- Style);
- verifyFormat("export namespace Foo\n"
- "{};",
- Style);
- verifyFormat("namespace Foo\n"
- "{\n"
- "void Bar();\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, NeverMergeShortRecords) {
- FormatStyle Style = getLLVMStyle();
-
- verifyFormat("class Foo {\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef class Foo {\n"
- " Foo();\n"
- "} Foo_t;",
- Style);
- verifyFormat("struct Foo {\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef struct Foo {\n"
- " Foo();\n"
- "} Foo_t;",
- Style);
- verifyFormat("union Foo {\n"
- " A,\n"
- "};",
- Style);
- verifyFormat("typedef union Foo {\n"
- " A,\n"
- "} Foo_t;",
- Style);
- verifyFormat("namespace Foo {\n"
- "void Bar();\n"
- "};",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- Style.BraceWrapping.AfterStruct = true;
- Style.BraceWrapping.AfterUnion = true;
- Style.BraceWrapping.AfterNamespace = true;
- verifyFormat("class Foo\n"
- "{\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef class Foo\n"
- "{\n"
- " Foo();\n"
- "} Foo_t;",
- Style);
- verifyFormat("struct Foo\n"
- "{\n"
- " Foo();\n"
- "};",
- Style);
- verifyFormat("typedef struct Foo\n"
- "{\n"
- " Foo();\n"
- "} Foo_t;",
- Style);
- verifyFormat("union Foo\n"
- "{\n"
- " A,\n"
- "};",
- Style);
- verifyFormat("typedef union Foo\n"
- "{\n"
- " A,\n"
- "} Foo_t;",
- Style);
- verifyFormat("namespace Foo\n"
- "{\n"
- "void Bar();\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, AllowShortRecordOnASingleLine) {
- auto Style = getLLVMStyle();
- EXPECT_EQ(Style.AllowShortRecordOnASingleLine,
- FormatStyle::SRS_EmptyAndAttached);
-
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Never;
- verifyFormat("class foo {\n"
- "};\n"
- "class bar {\n"
- " int i;\n"
- "};",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- verifyFormat("class foo\n"
- "{\n"
- "};\n"
- "class bar\n"
- "{\n"
- " int i;\n"
- "};",
- Style);
- Style.BraceWrapping.SplitEmptyRecord = false;
- verifyFormat("class foo\n"
- "{};",
- Style);
-
- Style = getLLVMStyle();
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Empty;
- verifyFormat("class foo {};\n"
- "class bar {\n"
- " int i;\n"
- "};",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- verifyFormat("class foo\n"
- "{\n"
- "};\n"
- "class bar\n"
- "{\n"
- " int i;\n"
- "};",
- Style);
- Style.BraceWrapping.SplitEmptyRecord = false;
- verifyFormat("class foo {};", Style);
-
- Style = getLLVMStyle();
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
- verifyFormat("class foo {};\n"
- "class bar { int i; };",
- Style);
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- verifyFormat("class foo\n"
- "{\n"
- "};\n"
- "class bar { int i; };",
- Style);
- Style.BraceWrapping.SplitEmptyRecord = false;
- verifyFormat("class foo {};", Style);
-
- Style = getLLVMStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
-
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Never;
- verifyFormat("class foo\n"
- "{ int i; };",
- Style);
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Empty;
- verifyFormat("class foo\n"
- "{ int i; };",
- Style);
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
- verifyFormat("class foo\n"
- "{\n"
- "};\n"
- "class foo { int i; };",
- Style);
-
- Style = getLLVMStyle();
- Style.BraceWrapping.SplitEmptyRecord = false;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterClass = true;
- Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
- verifyFormat("class foo\n"
- "{\n"
- " int i;\n"
- " int j;\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
- // Elaborate type variable declarations.
- verifyFormat("struct foo a = {bar};\nint n;");
- verifyFormat("class foo a = {bar};\nint n;");
- verifyFormat("union foo a = {bar};\nint n;");
-
- // Elaborate types inside function definitions.
- verifyFormat("struct foo f() {}\nint n;");
- verifyFormat("class foo f() {}\nint n;");
- verifyFormat("union foo f() {}\nint n;");
-
- // Templates.
- verifyFormat("template <class X> void f() {}\nint n;");
- verifyFormat("template <struct X> void f() {}\nint n;");
- verifyFormat("template <union X> void f() {}\nint n;");
-
- // Actual definitions...
- verifyFormat("struct {\n} n;");
- verifyFormat(
- "template <template <class T, class Y>, class Z> class X {\n} n;");
- verifyFormat("union Z {\n int n;\n} x;");
- verifyFormat("class MACRO Z {\n} n;");
- verifyFormat("class MACRO(X) Z {\n} n;");
- verifyFormat("class __attribute__((X)) Z {\n} n;");
- verifyFormat("class __declspec(X) Z {\n} n;");
- verifyFormat("class A##B##C {\n} n;");
- verifyFormat("class alignas(16) Z {\n} n;");
- verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
- verifyFormat("class MACROA MACRO(X) Z {\n} n;");
-
- // Redefinition from nested context:
- verifyFormat("class A::B::C {\n} n;");
-
- // Template definitions.
- verifyFormat(
- "template <typename F>\n"
- "Matcher(const Matcher<F> &Other,\n"
- " typename enable_if_c<is_base_of<F, T>::value &&\n"
- " !is_same<F, T>::value>::type * = 0)\n"
- " : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
-
- // FIXME: This is still incorrectly handled at the formatter side.
- verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
- verifyFormat("int i = SomeFunction(a<b, a> b);");
-
- verifyFormat("class A<int> f() {}\n"
- "int n;");
- verifyFormat("template <typename T> class A<T> f() {}\n"
- "int n;");
-
- verifyFormat("template <> class Foo<int> F() {\n"
- "} n;");
-
- // Elaborate types where incorrectly parsing the structural element would
- // break the indent.
- verifyFormat("if (true)\n"
- " class X x;\n"
- "else\n"
- " f();");
-
- // This is simply incomplete. Formatting is not important, but must not crash.
- verifyFormat("class A:");
-}
-
-TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
- verifyNoChange("#error Leave all white!!!!! space* alone!");
- verifyNoChange("#warning Leave all white!!!!! space* alone!");
- verifyFormat("#error 1", " # error 1");
- verifyFormat("#warning 1", " # warning 1");
-}
-
-TEST_F(FormatTest, FormatHashIfExpressions) {
- verifyFormat("#if AAAA && BBBB");
- verifyFormat("#if (AAAA && BBBB)");
- verifyFormat("#elif (AAAA && BBBB)");
- // FIXME: Come up with a better indentation for #elif.
- verifyFormat(
- "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n"
- " defined(BBBBBBBB)\n"
- "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n"
- " defined(BBBBBBBB)\n"
- "#endif",
- getLLVMStyleWithColumns(65));
-}
-
-TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
- FormatStyle AllowsMergedIf = getGoogleStyle();
- AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
- verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
- verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf);
- verifyFormat("if (true) return 42;", "if (true)\nreturn 42;", AllowsMergedIf);
- FormatStyle ShortMergedIf = AllowsMergedIf;
- ShortMergedIf.ColumnLimit = 25;
- verifyFormat("#define A \\\n"
- " if (true) return 42;",
- ShortMergedIf);
- verifyFormat("#define A \\\n"
- " f(); \\\n"
- " if (true)\n"
- "#define B",
- ShortMergedIf);
- verifyFormat("#define A \\\n"
- " f(); \\\n"
- " if (true)\n"
- "g();",
- ShortMergedIf);
- verifyFormat("{\n"
- "#ifdef A\n"
- " // Comment\n"
- " if (true) continue;\n"
- "#endif\n"
- " // Comment\n"
- " if (true) continue;\n"
- "}",
- ShortMergedIf);
- ShortMergedIf.ColumnLimit = 33;
- verifyFormat("#define A \\\n"
- " if constexpr (true) return 42;",
- ShortMergedIf);
- verifyFormat("#define A \\\n"
- " if CONSTEXPR (true) return 42;",
- ShortMergedIf);
- ShortMergedIf.ColumnLimit = 29;
- verifyFormat("#define A \\\n"
- " if (aaaaaaaaaa) return 1; \\\n"
- " return 2;",
- ShortMergedIf);
- ShortMergedIf.ColumnLimit = 28;
- verifyFormat("#define A \\\n"
- " if (aaaaaaaaaa) \\\n"
- " return 1; \\\n"
- " return 2;",
- ShortMergedIf);
- verifyFormat("#define A \\\n"
- " if constexpr (aaaaaaa) \\\n"
- " return 1; \\\n"
- " return 2;",
- ShortMergedIf);
- verifyFormat("#define A \\\n"
- " if CONSTEXPR (aaaaaaa) \\\n"
- " return 1; \\\n"
- " return 2;",
- ShortMergedIf);
-
- verifyFormat("//\n"
- "#define a \\\n"
- " if \\\n"
- " 0",
- getChromiumStyle(FormatStyle::LK_Cpp));
-}
-
-TEST_F(FormatTest, FormatStarDependingOnContext) {
- verifyFormat("void f(int *a);");
- verifyFormat("void f() { f(fint * b); }");
- verifyFormat("class A {\n void f(int *a);\n};");
- verifyFormat("class A {\n int *a;\n};");
- verifyFormat("namespace a {\n"
- "namespace b {\n"
- "class A {\n"
- " void f() {}\n"
- " int *a;\n"
- "};\n"
- "} // namespace b\n"
- "} // namespace a");
-}
-
-TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
- verifyFormat("while");
- verifyFormat("operator");
-}
-
-TEST_F(FormatTest, SkipsDeeplyNestedLines) {
- // This code would be painfully slow to format if we didn't skip it.
- std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
- "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
- "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
- "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
- "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
- "A(1, 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
- ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
- // Deeply nested part is untouched, rest is formatted.
- EXPECT_EQ(std::string("int i;") + Code + "int j;",
- format(std::string("int i;") + Code + "int j;",
- getLLVMStyle(), SC_ExpectIncomplete));
-}
-
-//===----------------------------------------------------------------------===//
-// Objective-C tests.
-//===----------------------------------------------------------------------===//
-
-TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
- verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
- verifyFormat("- (NSUInteger)indexOfObject:(id)anObject;",
- "-(NSUInteger)indexOfObject:(id)anObject;");
- verifyFormat("- (NSInteger)Mthod1;", "-(NSInteger)Mthod1;");
- verifyFormat("+ (id)Mthod2;", "+(id)Mthod2;");
- verifyFormat("- (NSInteger)Method3:(id)anObject;",
- "-(NSInteger)Method3:(id)anObject;");
- verifyFormat("- (NSInteger)Method4:(id)anObject;",
- "-(NSInteger)Method4:(id)anObject;");
- verifyFormat("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
- "-(NSInteger)Method5:(id)anObject:(id)AnotherObject;");
- verifyFormat("- (id)Method6:(id)A:(id)B:(id)C:(id)D;");
- verifyFormat("- (void)sendAction:(SEL)aSelector to:(id)anObject "
- "forAllCells:(BOOL)flag;");
-
- // Very long objectiveC method declaration.
- verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
- " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
- verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
- " inRange:(NSRange)range\n"
- " outRange:(NSRange)out_range\n"
- " outRange1:(NSRange)out_range1\n"
- " outRange2:(NSRange)out_range2\n"
- " outRange3:(NSRange)out_range3\n"
- " outRange4:(NSRange)out_range4\n"
- " outRange5:(NSRange)out_range5\n"
- " outRange6:(NSRange)out_range6\n"
- " outRange7:(NSRange)out_range7\n"
- " outRange8:(NSRange)out_range8\n"
- " outRange9:(NSRange)out_range9;");
-
- // When the function name has to be wrapped.
- FormatStyle Style = getLLVMStyle();
- // ObjC ignores IndentWrappedFunctionNames when wrapping methods
- // and always indents instead.
- Style.IndentWrappedFunctionNames = false;
- verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
- " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
- " anotherName:(NSString)bbbbbbbbbbbbbb {\n"
- "}",
- Style);
- Style.IndentWrappedFunctionNames = true;
- verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
- " veryLooooooooooongName:(NSString)cccccccccccccc\n"
- " anotherName:(NSString)dddddddddddddd {\n"
- "}",
- Style);
-
- verifyFormat("- (int)sum:(vector<int>)numbers;");
- verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
- // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
- // protocol lists (but not for template classes):
- // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
-
- verifyFormat("- (int (*)())foo:(int (*)())f;");
- verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
-
- // If there's no return type (very rare in practice!), LLVM and Google style
- // agree.
- verifyFormat("- foo;");
- verifyFormat("- foo:(int)f;");
- verifyGoogleFormat("- foo:(int)foo;");
-}
-
-TEST_F(FormatTest, SpaceBeforeObjCMethodDeclColon) {
- auto Style = getLLVMStyle();
- EXPECT_TRUE(Style.ObjCSpaceAfterMethodDeclarationPrefix);
- verifyFormat("- (void)method;", Style);
- Style.ObjCSpaceAfterMethodDeclarationPrefix = false;
- verifyFormat("-(void)method;", Style);
-}
-
-TEST_F(FormatTest, BreaksStringLiterals) {
- // FIXME: unstable test case
- EXPECT_EQ("\"some text \"\n"
- "\"other\";",
- format("\"some text other\";", getLLVMStyleWithColumns(12)));
- // FIXME: unstable test case
- EXPECT_EQ("\"some text \"\n"
- "\"other\";",
- format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
- verifyFormat("#define A \\\n"
- " \"some \" \\\n"
- " \"text \" \\\n"
- " \"other\";",
- "#define A \"some text other\";", getLLVMStyleWithColumns(12));
- verifyFormat("#define A \\\n"
- " \"so \" \\\n"
- " \"text \" \\\n"
- " \"other\";",
- "#define A \"so text other\";", getLLVMStyleWithColumns(12));
-
- verifyFormat("\"some text\"", getLLVMStyleWithColumns(1));
- verifyFormat("\"some text\"", getLLVMStyleWithColumns(11));
- // FIXME: unstable test case
- EXPECT_EQ("\"some \"\n"
- "\"text\"",
- format("\"some text\"", getLLVMStyleWithColumns(10)));
- // FIXME: unstable test case
- EXPECT_EQ("\"some \"\n"
- "\"text\"",
- format("\"some text\"", getLLVMStyleWithColumns(7)));
- // FIXME: unstable test case
- EXPECT_EQ("\"some\"\n"
- "\" tex\"\n"
- "\"t\"",
- format("\"some text\"", getLLVMStyleWithColumns(6)));
- // FIXME: unstable test case
- EXPECT_EQ("\"some\"\n"
- "\" tex\"\n"
- "\" and\"",
- format("\"some tex and\"", getLLVMStyleWithColumns(6)));
- // FIXME: unstable test case
- EXPECT_EQ("\"some\"\n"
- "\"/tex\"\n"
- "\"/and\"",
- format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
-
- verifyFormat("variable =\n"
- " \"long string \"\n"
- " \"literal\";",
- "variable = \"long string literal\";",
- getLLVMStyleWithColumns(20));
-
- verifyFormat("variable = f(\n"
- " \"long string \"\n"
- " \"literal\",\n"
- " short,\n"
- " loooooooooooooooooooong);",
- "variable = f(\"long string literal\", short, "
- "loooooooooooooooooooong);",
- getLLVMStyleWithColumns(20));
-
- verifyFormat("f(g(\"long string \"\n"
- " \"literal\"),\n"
- " b);",
- "f(g(\"long string literal\"), b);",
- getLLVMStyleWithColumns(20));
- verifyFormat("f(g(\"long string \"\n"
- " \"literal\",\n"
- " a),\n"
- " b);",
- "f(g(\"long string literal\", a), b);",
- getLLVMStyleWithColumns(20));
- verifyFormat("f(\"one two\".split(\n"
- " variable));",
- "f(\"one two\".split(variable));", getLLVMStyleWithColumns(20));
- verifyFormat("f(\"one two three four five six \"\n"
- " \"seven\".split(\n"
- " really_looooong_variable));",
- "f(\"one two three four five six seven\"."
- "split(really_looooong_variable));",
- getLLVMStyleWithColumns(33));
-
- verifyFormat("f(\"some \"\n"
- " \"text\",\n"
- " other);",
- "f(\"some text\", other);", getLLVMStyleWithColumns(10));
-
- // Only break as a last resort.
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
-
- // FIXME: unstable test case
- EXPECT_EQ("\"splitmea\"\n"
- "\"trandomp\"\n"
- "\"oint\"",
- format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
-
- // FIXME: unstable test case
- EXPECT_EQ("\"split/\"\n"
- "\"pathat/\"\n"
- "\"slashes\"",
- format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
-
- // FIXME: unstable test case
- EXPECT_EQ("\"split/\"\n"
- "\"pathat/\"\n"
- "\"slashes\"",
- format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
- // FIXME: unstable test case
- EXPECT_EQ("\"split at \"\n"
- "\"spaces/at/\"\n"
- "\"slashes.at.any$\"\n"
- "\"non-alphanumeric%\"\n"
- "\"1111111111characte\"\n"
- "\"rs\"",
- format("\"split at "
- "spaces/at/"
- "slashes.at."
- "any$non-"
- "alphanumeric%"
- "1111111111characte"
- "rs\"",
- getLLVMStyleWithColumns(20)));
-
- // Verify that splitting the strings understands
- // Style::AlwaysBreakBeforeMultilineStrings.
- verifyFormat("aaaaaaaaaaaa(\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
- "aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaaa\");",
- getGoogleStyle());
- verifyFormat("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
- "return \"aaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaaa\";",
- getGoogleStyle());
- verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
- "llvm::outs() << "
- "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
- "aaaaaaaaaaaaaaaaaaa\";");
- verifyFormat("ffff(\n"
- " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
- " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
- "ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
- getGoogleStyle());
-
- FormatStyle Style = getLLVMStyleWithColumns(12);
- Style.BreakStringLiterals = false;
- verifyFormat("\"some text other\";", Style);
-
- FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
- AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- verifyFormat("#define A \\\n"
- " \"some \" \\\n"
- " \"text \" \\\n"
- " \"other\";",
- "#define A \"some text other\";", AlignLeft);
-}
-
-TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
- verifyFormat("C a = \"some more \"\n"
- " \"text\";",
- "C a = \"some more text\";", getLLVMStyleWithColumns(18));
-}
-
-TEST_F(FormatTest, FullyRemoveEmptyLines) {
- FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
- NoEmptyLines.MaxEmptyLinesToKeep = 0;
- verifyFormat("int i = a(b());", "int i=a(\n\n b(\n\n\n )\n\n);",
- NoEmptyLines);
-}
-
-TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
- // FIXME: unstable test case
- EXPECT_EQ(
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- "(\n"
- " \"x\t\");",
- format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- "aaaaaaa("
- "\"x\t\");"));
-}
-
-TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
- // FIXME: unstable test case
- EXPECT_EQ(
- "u8\"utf8 string \"\n"
- "u8\"literal\";",
- format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
- // FIXME: unstable test case
- EXPECT_EQ(
- "u\"utf16 string \"\n"
- "u\"literal\";",
- format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
- // FIXME: unstable test case
- EXPECT_EQ(
- "U\"utf32 string \"\n"
- "U\"literal\";",
- format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
- // FIXME: unstable test case
- EXPECT_EQ("L\"wide string \"\n"
- "L\"literal\";",
- format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
- verifyFormat("@\"NSString \"\n"
- "@\"literal\";",
- "@\"NSString literal\";", getGoogleStyleWithColumns(19));
- verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
-
- // This input makes clang-format try to split the incomplete unicode escape
- // sequence, which used to lead to a crasher.
- verifyNoCrash(
- "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- getLLVMStyleWithColumns(60));
-}
-
-TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
- FormatStyle Style = getGoogleStyleWithColumns(15);
- verifyFormat("R\"x(raw literal)x\";", Style);
- verifyFormat("uR\"x(raw literal)x\";", Style);
- verifyFormat("LR\"x(raw literal)x\";", Style);
- verifyFormat("UR\"x(raw literal)x\";", Style);
- verifyFormat("u8R\"x(raw literal)x\";", Style);
-}
-
-TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
- FormatStyle Style = getLLVMStyleWithColumns(20);
- // FIXME: unstable test case
- EXPECT_EQ(
- "_T(\"aaaaaaaaaaaaaa\")\n"
- "_T(\"aaaaaaaaaaaaaa\")\n"
- "_T(\"aaaaaaaaaaaa\")",
- format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
- verifyFormat("f(x,\n"
- " _T(\"aaaaaaaaaaaa\")\n"
- " _T(\"aaa\"),\n"
- " z);",
- "f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style);
-
- // FIXME: Handle embedded spaces in one iteration.
- // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
- // "_T(\"aaaaaaaaaaaaa\")\n"
- // "_T(\"aaaaaaaaaaaaa\")\n"
- // "_T(\"a\")",
- // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
- // getLLVMStyleWithColumns(20)));
- verifyFormat("_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
- " _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style);
- verifyFormat("f(\n"
- "#if !TEST\n"
- " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
- "#endif\n"
- ");",
- "f(\n"
- "#if !TEST\n"
- "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
- "#endif\n"
- ");");
- verifyFormat("f(\n"
- "\n"
- " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
- "f(\n"
- "\n"
- "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));");
- // Regression test for accessing tokens past the end of a vector in the
- // TokenLexer.
- verifyNoCrash(R"(_T(
-"
-)
-)");
-}
-
-TEST_F(FormatTest, BreaksStringLiteralOperands) {
- // In a function call with two operands, the second can be broken with no line
- // break before it.
- verifyFormat("func(a, \"long long \"\n"
- " \"long long\");",
- "func(a, \"long long long long\");",
- getLLVMStyleWithColumns(24));
- // In a function call with three operands, the second must be broken with a
- // line break before it.
- verifyFormat("func(a,\n"
- " \"long long long \"\n"
- " \"long\",\n"
- " c);",
- "func(a, \"long long long long\", c);",
- getLLVMStyleWithColumns(24));
- // In a function call with three operands, the third must be broken with a
- // line break before it.
- verifyFormat("func(a, b,\n"
- " \"long long long \"\n"
- " \"long\");",
- "func(a, b, \"long long long long\");",
- getLLVMStyleWithColumns(24));
- // In a function call with three operands, both the second and the third must
- // be broken with a line break before them.
- verifyFormat("func(a,\n"
- " \"long long long \"\n"
- " \"long\",\n"
- " \"long long long \"\n"
- " \"long\");",
- "func(a, \"long long long long\", \"long long long long\");",
- getLLVMStyleWithColumns(24));
- // In a chain of << with two operands, the second can be broken with no line
- // break before it.
- verifyFormat("a << \"line line \"\n"
- " \"line\";",
- "a << \"line line line\";", getLLVMStyleWithColumns(20));
- // In a chain of << with three operands, the second can be broken with no line
- // break before it.
- verifyFormat("abcde << \"line \"\n"
- " \"line line\"\n"
- " << c;",
- "abcde << \"line line line\" << c;",
- getLLVMStyleWithColumns(20));
- // In a chain of << with three operands, the third must be broken with a line
- // break before it.
- verifyFormat("a << b\n"
- " << \"line line \"\n"
- " \"line\";",
- "a << b << \"line line line\";", getLLVMStyleWithColumns(20));
- // In a chain of << with three operands, the second can be broken with no line
- // break before it and the third must be broken with a line break before it.
- verifyFormat("abcd << \"line line \"\n"
- " \"line\"\n"
- " << \"line line \"\n"
- " \"line\";",
- "abcd << \"line line line\" << \"line line line\";",
- getLLVMStyleWithColumns(20));
- // In a chain of binary operators with two operands, the second can be broken
- // with no line break before it.
- verifyFormat("abcd + \"line line \"\n"
- " \"line line\";",
- "abcd + \"line line line line\";", getLLVMStyleWithColumns(20));
- // In a chain of binary operators with three operands, the second must be
- // broken with a line break before it.
- verifyFormat("abcd +\n"
- " \"line line \"\n"
- " \"line line\" +\n"
- " e;",
- "abcd + \"line line line line\" + e;",
- getLLVMStyleWithColumns(20));
- // In a function call with two operands, with AlignAfterOpenBracket enabled,
- // the first must be broken with a line break before it.
- FormatStyle Style = getLLVMStyleWithColumns(25);
- Style.BreakAfterOpenBracketFunction = true;
- verifyFormat("someFunction(\n"
- " \"long long long \"\n"
- " \"long\",\n"
- " a);",
- "someFunction(\"long long long long\", a);", Style);
- Style.BreakAfterOpenBracketFunction = true;
- Style.BreakBeforeCloseBracketFunction = true;
- verifyFormat("someFunction(\n"
- " \"long long long \"\n"
- " \"long\",\n"
- " a\n"
- ");",
- Style);
-}
-
-TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
- verifyFormat("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
- "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";");
-}
-
-TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
- verifyFormat("f(g(R\"x(raw literal)x\", a), b);",
- "f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle());
- verifyFormat("fffffffffff(g(R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\",\n"
- " a),\n"
- " b);",
- "fffffffffff(g(R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\", a), b);",
- getGoogleStyleWithColumns(20));
- verifyFormat("fffffffffff(\n"
- " g(R\"x(qqq\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\",\n"
- " a),\n"
- " b);",
- "fffffffffff(g(R\"x(qqq\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\", a), b);",
- getGoogleStyleWithColumns(20));
-
- verifyNoChange("fffffffffff(R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\");",
- getGoogleStyleWithColumns(20));
- verifyFormat("fffffffffff(R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\" + bbbbbb);",
- "fffffffffff(R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\" + bbbbbb);",
- getGoogleStyleWithColumns(20));
- verifyFormat("fffffffffff(\n"
- " R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\" +\n"
- " bbbbbb);",
- "fffffffffff(\n"
- " R\"x(\n"
- "multiline raw string literal xxxxxxxxxxxxxx\n"
- ")x\" + bbbbbb);",
- getGoogleStyleWithColumns(20));
- verifyFormat("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
- "fffffffffff(\n"
- " R\"(single line raw string)\" + bbbbbb);");
-}
-
-TEST_F(FormatTest, SkipsUnknownStringLiterals) {
- verifyFormat("string a = \"unterminated;");
- verifyFormat("function(\"unterminated,\n"
- " OtherParameter);",
- "function( \"unterminated,\n"
- " OtherParameter);");
-}
-
-TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
- FormatStyle Style = getLLVMStyle();
- Style.Standard = FormatStyle::LS_Cpp03;
- verifyFormat("#define x(_a) printf(\"foo\" _a);",
- "#define x(_a) printf(\"foo\"_a);", Style);
-}
-
-TEST_F(FormatTest, CppLexVersion) {
- FormatStyle Style = getLLVMStyle();
- // Formatting of x * y differs if x is a type.
- verifyFormat("void foo() { MACRO(a * b); }", Style);
- verifyFormat("void foo() { MACRO(int *b); }", Style);
-
- // LLVM style uses latest lexer.
- verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
- Style.Standard = FormatStyle::LS_Cpp17;
- // But in c++17, char8_t isn't a keyword.
- verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
-}
-
-TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
-
-TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
- verifyFormat("someFunction(\"aaabbbcccd\"\n"
- " \"ddeeefff\");",
- "someFunction(\"aaabbbcccdddeeefff\");",
- getLLVMStyleWithColumns(25));
- verifyFormat("someFunction1234567890(\n"
- " \"aaabbbcccdddeeefff\");",
- "someFunction1234567890(\"aaabbbcccdddeeefff\");",
- getLLVMStyleWithColumns(26));
- verifyFormat("someFunction1234567890(\n"
- " \"aaabbbcccdddeeeff\"\n"
- " \"f\");",
- "someFunction1234567890(\"aaabbbcccdddeeefff\");",
- getLLVMStyleWithColumns(25));
- verifyFormat("someFunction1234567890(\n"
- " \"aaabbbcccdddeeeff\"\n"
- " \"f\");",
- "someFunction1234567890(\"aaabbbcccdddeeefff\");",
- getLLVMStyleWithColumns(24));
- verifyFormat("someFunction(\n"
- " \"aaabbbcc ddde \"\n"
- " \"efff\");",
- "someFunction(\"aaabbbcc ddde efff\");",
- getLLVMStyleWithColumns(25));
- verifyFormat("someFunction(\"aaabbbccc \"\n"
- " \"ddeeefff\");",
- "someFunction(\"aaabbbccc ddeeefff\");",
- getLLVMStyleWithColumns(25));
- verifyFormat("someFunction1234567890(\n"
- " \"aaabb \"\n"
- " \"cccdddeeefff\");",
- "someFunction1234567890(\"aaabb cccdddeeefff\");",
- getLLVMStyleWithColumns(25));
- verifyFormat("#define A \\\n"
- " string s = \\\n"
- " \"123456789\" \\\n"
- " \"0\"; \\\n"
- " int i;",
- "#define A string s = \"1234567890\"; int i;",
- getLLVMStyleWithColumns(20));
- verifyFormat("someFunction(\n"
- " \"aaabbbcc \"\n"
- " \"dddeeefff\");",
- "someFunction(\"aaabbbcc dddeeefff\");",
- getLLVMStyleWithColumns(25));
-}
-
-TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
- verifyFormat("\"\\a\"", getLLVMStyleWithColumns(3));
- verifyFormat("\"\\\"", getLLVMStyleWithColumns(2));
- // FIXME: unstable test case
- EXPECT_EQ("\"test\"\n"
- "\"\\n\"",
- format("\"test\\n\"", getLLVMStyleWithColumns(7)));
- // FIXME: unstable test case
- EXPECT_EQ("\"tes\\\\\"\n"
- "\"n\"",
- format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
- // FIXME: unstable test case
- EXPECT_EQ("\"\\\\\\\\\"\n"
- "\"\\n\"",
- format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
- verifyFormat("\"\\uff01\"", getLLVMStyleWithColumns(7));
- // FIXME: unstable test case
- EXPECT_EQ("\"\\uff01\"\n"
- "\"test\"",
- format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
- verifyFormat("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11));
- // FIXME: unstable test case
- EXPECT_EQ("\"\\x000000000001\"\n"
- "\"next\"",
- format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
- verifyFormat("\"\\x000000000001next\"", getLLVMStyleWithColumns(15));
- verifyFormat("\"\\x000000000001\"", getLLVMStyleWithColumns(7));
- // FIXME: unstable test case
- EXPECT_EQ("\"test\"\n"
- "\"\\000000\"\n"
- "\"000001\"",
- format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
- // FIXME: unstable test case
- EXPECT_EQ("\"test\\000\"\n"
- "\"00000000\"\n"
- "\"1\"",
- format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
-}
-
-TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
- verifyFormat("void f() {\n"
- " return g() {}\n"
- " void h() {}");
- verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
- "g();\n"
- "}");
-}
-
-TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
- verifyFormat(
- "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
-}
-
-TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
- verifyFormat("class X {\n"
- " void f() {\n"
- " }\n"
- "};",
- getLLVMStyleWithColumns(12));
-}
-
-TEST_F(FormatTest, ConfigurableIndentWidth) {
- FormatStyle EightIndent = getLLVMStyleWithColumns(18);
- EightIndent.IndentWidth = 8;
- EightIndent.ContinuationIndentWidth = 8;
- verifyFormat("void f() {\n"
- " someFunction();\n"
- " if (true) {\n"
- " f();\n"
- " }\n"
- "}",
- EightIndent);
- verifyFormat("class X {\n"
- " void f() {\n"
- " }\n"
- "};",
- EightIndent);
- verifyFormat("int x[] = {\n"
- " call(),\n"
- " call()};",
- EightIndent);
-}
-
-TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
- verifyFormat("double\n"
- "f();",
- getLLVMStyleWithColumns(8));
-}
-
-TEST_F(FormatTest, ConfigurableUseOfTab) {
- FormatStyle Tab = getLLVMStyleWithColumns(42);
- Tab.IndentWidth = 8;
- Tab.UseTab = FormatStyle::UT_Always;
- Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
-
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb)\t\t// w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("if (aaa && bbb) // w\n"
- "\t;",
- "if(aaa&&bbb)// w\n"
- ";",
- Tab);
-
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("#define A \\\n"
- "\tvoid f() { \\\n"
- "\t\tsomeFunction( \\\n"
- "\t\t parameter1, \\\n"
- "\t\t parameter2); \\\n"
- "\t}",
- Tab);
- verifyFormat("int a;\t // x\n"
- "int bbbbbbbb; // x",
- Tab);
-
- FormatStyle TabAlignment = Tab;
- TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
- TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("unsigned long long big;\n"
- "char*\t\t ptr;",
- TabAlignment);
- TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("unsigned long long big;\n"
- "char *\t\t ptr;",
- TabAlignment);
- TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
- verifyFormat("unsigned long long big;\n"
- "char\t\t *ptr;",
- TabAlignment);
-
- Tab.TabWidth = 4;
- Tab.IndentWidth = 8;
- verifyFormat("class TabWidth4Indent8 {\n"
- "\t\tvoid f() {\n"
- "\t\t\t\tsomeFunction(parameter1,\n"
- "\t\t\t\t\t\t\t parameter2);\n"
- "\t\t}\n"
- "};",
- Tab);
-
- Tab.TabWidth = 4;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth4Indent4 {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t\t\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
-
- Tab.TabWidth = 8;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth8Indent4 {\n"
- " void f() {\n"
- "\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- " }\n"
- "};",
- Tab);
-
- Tab.TabWidth = 8;
- Tab.IndentWidth = 8;
- verifyFormat("/*\n"
- "\t a\t\tcomment\n"
- "\t in multiple lines\n"
- " */",
- " /*\t \t \n"
- " \t \t a\t\tcomment\t \t\n"
- " \t \t in multiple lines\t\n"
- " \t */",
- Tab);
-
- TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
- TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("void f() {\n"
- "\tunsigned long long big;\n"
- "\tchar* ptr;\n"
- "}",
- TabAlignment);
- TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("void f() {\n"
- "\tunsigned long long big;\n"
- "\tchar * ptr;\n"
- "}",
- TabAlignment);
- TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
- verifyFormat("void f() {\n"
- "\tunsigned long long big;\n"
- "\tchar *ptr;\n"
- "}",
- TabAlignment);
-
- Tab.UseTab = FormatStyle::UT_ForIndentation;
- verifyFormat("{\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "};",
- Tab);
- verifyFormat("enum AA {\n"
- "\ta1, // Force multiple lines\n"
- "\ta2,\n"
- "\ta3\n"
- "};",
- Tab);
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb) // w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("{\n"
- "\tQ(\n"
- "\t {\n"
- "\t\t int a;\n"
- "\t\t someFunction(aaaaaaaa,\n"
- "\t\t bbbbbbb);\n"
- "\t },\n"
- "\t p);\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/* aaaa\n"
- "\t bbbb */\n"
- "}",
- "{\n"
- "/* aaaa\n"
- " bbbb */\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "/*\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "*/\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t// bbbbbbbbbbbbb\n"
- "}",
- "{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- "\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- " asdf\n"
- "\t*/\n"
- "}",
- Tab);
-
- verifyFormat("void f() {\n"
- "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
- "\t : bbbbbbbbbbbbbbbbbb\n"
- "}",
- Tab);
- FormatStyle TabNoBreak = Tab;
- TabNoBreak.BreakBeforeTernaryOperators = false;
- verifyFormat("void f() {\n"
- "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
- "\t bbbbbbbbbbbbbbbbbb\n"
- "}",
- TabNoBreak);
- verifyFormat("void f() {\n"
- "\treturn true ?\n"
- "\t aaaaaaaaaaaaaaaaaaaa :\n"
- "\t bbbbbbbbbbbbbbbbbbbb\n"
- "}",
- TabNoBreak);
-
- Tab.UseTab = FormatStyle::UT_Never;
- verifyFormat("/*\n"
- " a\t\tcomment\n"
- " in multiple lines\n"
- " */",
- " /*\t \t \n"
- " \t \t a\t\tcomment\t \t\n"
- " \t \t in multiple lines\t\n"
- " \t */",
- Tab);
- verifyFormat("/* some\n"
- " comment */",
- " \t \t /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("int a; /* some\n"
- " comment */",
- " \t \t int a; /* some\n"
- " \t \t comment */",
- Tab);
-
- verifyFormat("int a; /* some\n"
- "comment */",
- " \t \t int\ta; /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("f(\"\t\t\"); /* some\n"
- " comment */",
- " \t \t f(\"\t\t\"); /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("{\n"
- " /*\n"
- " * Comment\n"
- " */\n"
- " int i;\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t * Comment\n"
- "\t */\n"
- "\t int i;\n"
- "}",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
- Tab.TabWidth = 8;
- Tab.IndentWidth = 8;
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb) // w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("if (aaa && bbb) // w\n"
- "\t;",
- "if(aaa&&bbb)// w\n"
- ";",
- Tab);
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("#define A \\\n"
- "\tvoid f() { \\\n"
- "\t\tsomeFunction( \\\n"
- "\t\t parameter1, \\\n"
- "\t\t parameter2); \\\n"
- "\t}",
- Tab);
- Tab.TabWidth = 4;
- Tab.IndentWidth = 8;
- verifyFormat("class TabWidth4Indent8 {\n"
- "\t\tvoid f() {\n"
- "\t\t\t\tsomeFunction(parameter1,\n"
- "\t\t\t\t\t\t\t parameter2);\n"
- "\t\t}\n"
- "};",
- Tab);
- Tab.TabWidth = 4;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth4Indent4 {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t\t\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- Tab.TabWidth = 8;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth8Indent4 {\n"
- " void f() {\n"
- "\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- " }\n"
- "};",
- Tab);
- Tab.TabWidth = 8;
- Tab.IndentWidth = 8;
- verifyFormat("/*\n"
- "\t a\t\tcomment\n"
- "\t in multiple lines\n"
- " */",
- " /*\t \t \n"
- " \t \t a\t\tcomment\t \t\n"
- " \t \t in multiple lines\t\n"
- " \t */",
- Tab);
- verifyFormat("{\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "};",
- Tab);
- verifyFormat("enum AA {\n"
- "\ta1, // Force multiple lines\n"
- "\ta2,\n"
- "\ta3\n"
- "};",
- Tab);
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb) // w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("{\n"
- "\tQ(\n"
- "\t {\n"
- "\t\t int a;\n"
- "\t\t someFunction(aaaaaaaa,\n"
- "\t\t\t\t bbbbbbb);\n"
- "\t },\n"
- "\t p);\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/* aaaa\n"
- "\t bbbb */\n"
- "}",
- "{\n"
- "/* aaaa\n"
- " bbbb */\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "/*\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "*/\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t// bbbbbbbbbbbbb\n"
- "}",
- "{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- "\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- " asdf\n"
- "\t*/\n"
- "}",
- Tab);
- verifyFormat("/* some\n"
- " comment */",
- " \t \t /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("int a; /* some\n"
- " comment */",
- " \t \t int a; /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("int a; /* some\n"
- "comment */",
- " \t \t int\ta; /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("f(\"\t\t\"); /* some\n"
- " comment */",
- " \t \t f(\"\t\t\"); /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t * Comment\n"
- "\t */\n"
- "\tint i;\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t * Comment\n"
- "\t */\n"
- "\t int i;\n"
- "}",
- Tab);
- Tab.TabWidth = 2;
- Tab.IndentWidth = 2;
- verifyFormat("{\n"
- "\t/* aaaa\n"
- "\t\t bbbb */\n"
- "}",
- "{\n"
- "/* aaaa\n"
- "\t bbbb */\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t\tbbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "/*\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "*/\n"
- "}",
- Tab);
- Tab.AlignConsecutiveAssignments.Enabled = true;
- Tab.AlignConsecutiveDeclarations.Enabled = true;
- Tab.TabWidth = 4;
- Tab.IndentWidth = 4;
- verifyFormat("class Assign {\n"
- "\tvoid f() {\n"
- "\t\tint x = 123;\n"
- "\t\tint random = 4;\n"
- "\t\tstd::string alphabet =\n"
- "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
- "\t}\n"
- "};",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
- Tab.TabWidth = 8;
- Tab.IndentWidth = 8;
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb) // w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("if (aaa && bbb) // w\n"
- "\t;",
- "if(aaa&&bbb)// w\n"
- ";",
- Tab);
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("#define A \\\n"
- "\tvoid f() { \\\n"
- "\t\tsomeFunction( \\\n"
- "\t\t parameter1, \\\n"
- "\t\t parameter2); \\\n"
- "\t}",
- Tab);
- Tab.TabWidth = 4;
- Tab.IndentWidth = 8;
- verifyFormat("class TabWidth4Indent8 {\n"
- "\t\tvoid f() {\n"
- "\t\t\t\tsomeFunction(parameter1,\n"
- "\t\t\t\t parameter2);\n"
- "\t\t}\n"
- "};",
- Tab);
- Tab.TabWidth = 4;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth4Indent4 {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- Tab.TabWidth = 8;
- Tab.IndentWidth = 4;
- verifyFormat("class TabWidth8Indent4 {\n"
- " void f() {\n"
- "\tsomeFunction(parameter1,\n"
- "\t parameter2);\n"
- " }\n"
- "};",
- Tab);
- Tab.TabWidth = 8;
- Tab.IndentWidth = 8;
- verifyFormat("/*\n"
- " a\t\tcomment\n"
- " in multiple lines\n"
- " */",
- " /*\t \t \n"
- " \t \t a\t\tcomment\t \t\n"
- " \t \t in multiple lines\t\n"
- " \t */",
- Tab);
- verifyFormat("{\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
- "};",
- Tab);
- verifyFormat("enum AA {\n"
- "\ta1, // Force multiple lines\n"
- "\ta2,\n"
- "\ta3\n"
- "};",
- Tab);
- verifyFormat("if (aaaaaaaa && // q\n"
- " bb) // w\n"
- "\t;",
- "if (aaaaaaaa &&// q\n"
- "bb)// w\n"
- ";",
- Tab);
- verifyFormat("class X {\n"
- "\tvoid f() {\n"
- "\t\tsomeFunction(parameter1,\n"
- "\t\t parameter2);\n"
- "\t}\n"
- "};",
- Tab);
- verifyFormat("{\n"
- "\tQ(\n"
- "\t {\n"
- "\t\t int a;\n"
- "\t\t someFunction(aaaaaaaa,\n"
- "\t\t bbbbbbb);\n"
- "\t },\n"
- "\t p);\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/* aaaa\n"
- "\t bbbb */\n"
- "}",
- "{\n"
- "/* aaaa\n"
- " bbbb */\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "/*\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "*/\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t// bbbbbbbbbbbbb\n"
- "}",
- "{\n"
- "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- "\n"
- "\t*/\n"
- "}",
- Tab);
- verifyNoChange("{\n"
- "\t/*\n"
- " asdf\n"
- "\t*/\n"
- "}",
- Tab);
- verifyFormat("/* some\n"
- " comment */",
- " \t \t /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("int a; /* some\n"
- " comment */",
- " \t \t int a; /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("int a; /* some\n"
- "comment */",
- " \t \t int\ta; /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("f(\"\t\t\"); /* some\n"
- " comment */",
- " \t \t f(\"\t\t\"); /* some\n"
- " \t \t comment */",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t * Comment\n"
- "\t */\n"
- "\tint i;\n"
- "}",
- "{\n"
- "\t/*\n"
- "\t * Comment\n"
- "\t */\n"
- "\t int i;\n"
- "}",
- Tab);
- Tab.TabWidth = 2;
- Tab.IndentWidth = 2;
- verifyFormat("{\n"
- "\t/* aaaa\n"
- "\t bbbb */\n"
- "}",
- "{\n"
- "/* aaaa\n"
- " bbbb */\n"
- "}",
- Tab);
- verifyFormat("{\n"
- "\t/*\n"
- "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
- "\t bbbbbbbbbbbbb\n"
- "\t*/\n"
- "}",
- "{\n"
- "/*\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
- "*/\n"
- "}",
- Tab);
- Tab.AlignConsecutiveAssignments.Enabled = true;
- Tab.AlignConsecutiveDeclarations.Enabled = true;
- Tab.TabWidth = 4;
- Tab.IndentWidth = 4;
- verifyFormat("class Assign {\n"
- "\tvoid f() {\n"
- "\t\tint x = 123;\n"
- "\t\tint random = 4;\n"
- "\t\tstd::string alphabet =\n"
- "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
- "\t}\n"
- "};",
- Tab);
- Tab.AlignOperands = FormatStyle::OAS_Align;
- verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
- " cccccccccccccccccccc;",
- Tab);
- // no alignment
- verifyFormat("int aaaaaaaaaa =\n"
- "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
- Tab);
- verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
- " : bbbbbbbbbbbbbb ? 222222222222222\n"
- " : 333333333333333;",
- Tab);
- Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
- verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
- " + cccccccccccccccccccc;",
- Tab);
-
- Tab.BreakBeforeBraces = FormatStyle::BS_Custom;
- Tab.BraceWrapping.BeforeLambdaBody = true;
- verifyNoChange("example(\n"
- "\t[]\n"
- "\t{\n"
- "\t\t// foo\n"
- "\t\t// bar\n"
- "\t});",
- Tab);
-}
-
-TEST_F(FormatTest, ZeroTabWidth) {
- FormatStyle Tab = getLLVMStyleWithColumns(42);
- Tab.IndentWidth = 8;
- Tab.UseTab = FormatStyle::UT_Never;
- Tab.TabWidth = 0;
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t// line starts with '\t'\n"
- "};",
- Tab);
-
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t\t// line starts with '\t'\n"
- "};",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_ForIndentation;
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t// line starts with '\t'\n"
- "};",
- Tab);
-
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t\t// line starts with '\t'\n"
- "};",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t// line starts with '\t'\n"
- "};",
- Tab);
-
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t\t// line starts with '\t'\n"
- "};",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t// line starts with '\t'\n"
- "};",
- Tab);
-
- verifyFormat("void a() {\n"
- " // line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t\t// line starts with '\t'\n"
- "};",
- Tab);
-
- Tab.UseTab = FormatStyle::UT_Always;
- verifyFormat("void a() {\n"
- "// line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t// line starts with '\t'\n"
- "};",
- Tab);
-
- verifyFormat("void a() {\n"
- "// line starts with '\t'\n"
- "};",
- "void a(){\n"
- "\t\t// line starts with '\t'\n"
- "};",
- Tab);
-}
-
-TEST_F(FormatTest, CalculatesOriginalColumn) {
- verifyFormat("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "q\"; /* some\n"
- " comment */",
- " \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "q\"; /* some\n"
- " comment */");
- verifyFormat("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
- "/* some\n"
- " comment */",
- "// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
- " /* some\n"
- " comment */");
- verifyFormat("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "qqq\n"
- "/* some\n"
- " comment */",
- "// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "qqq\n"
- " /* some\n"
- " comment */");
- verifyFormat("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "wwww; /* some\n"
- " comment */",
- " inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
- "wwww; /* some\n"
- " comment */");
-}
-
-TEST_F(FormatTest, SpaceAfterOperatorKeyword) {
- auto SpaceAfterOperatorKeyword = getLLVMStyle();
- SpaceAfterOperatorKeyword.SpaceAfterOperatorKeyword = true;
- verifyFormat("bool operator ++(int a);", SpaceAfterOperatorKeyword);
-}
-
-TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
- FormatStyle NoSpace = getLLVMStyle();
- NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
-
- verifyFormat("while(true)\n"
- " continue;",
- NoSpace);
- verifyFormat("for(;;)\n"
- " continue;",
- NoSpace);
- verifyFormat("if(true)\n"
- " f();\n"
- "else if(true)\n"
- " f();",
- NoSpace);
- verifyFormat("do {\n"
- " do_something();\n"
- "} while(something());",
- NoSpace);
- verifyFormat("switch(x) {\n"
- "default:\n"
- " break;\n"
- "}",
- NoSpace);
- verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
- verifyFormat("size_t x = sizeof(x);", NoSpace);
- verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
- verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
- verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
- verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
- verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
- verifyFormat("alignas(128) char a[128];", NoSpace);
- verifyFormat("size_t x = alignof(MyType);", NoSpace);
- verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
- verifyFormat("int f() throw(Deprecated);", NoSpace);
- verifyFormat("typedef void (*cb)(int);", NoSpace);
- verifyFormat("T A::operator()();", NoSpace);
- verifyFormat("X A::operator++(T);", NoSpace);
- verifyFormat("auto lambda = []() { return 0; };", NoSpace);
- verifyFormat("#if (foo || bar) && baz\n"
- "#elif ((a || b) && c) || d\n"
- "#endif",
- NoSpace);
- // Space between sizeof and C compound literal.
- verifyFormat("a = sizeof (int){};", NoSpace);
-
- FormatStyle Space = getLLVMStyle();
- Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
-
- verifyFormat("int f ();", Space);
- verifyFormat("bool operator< ();", Space);
- verifyFormat("bool operator> ();", Space);
- verifyFormat("void f (int a, T b) {\n"
- " while (true)\n"
- " continue;\n"
- "}",
- Space);
- verifyFormat("if (true)\n"
- " f ();\n"
- "else if (true)\n"
- " f ();",
- Space);
- verifyFormat("do {\n"
- " do_something ();\n"
- "} while (something ());",
- Space);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- Space);
- verifyFormat("A::A () : a (1) {}", Space);
- verifyFormat("void f () __attribute__ ((asdf));", Space);
- verifyFormat("*(&a + 1);\n"
- "&((&a)[1]);\n"
- "a[(b + c) * d];\n"
- "(((a + 1) * 2) + 3) * 4;",
- Space);
- verifyFormat("#define A(x) x", Space);
- verifyFormat("#define A (x) x", Space);
- verifyFormat("#if defined(x)\n"
- "#endif",
- Space);
- verifyFormat("auto i = std::make_unique<int> (5);", Space);
- verifyFormat("size_t x = sizeof (x);", Space);
- verifyFormat("auto f (int x) -> decltype (x);", Space);
- verifyFormat("auto f (int x) -> typeof (x);", Space);
- verifyFormat("auto f (int x) -> _Atomic (x);", Space);
- verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
- verifyFormat("int f (T x) noexcept (x.create ());", Space);
- verifyFormat("alignas (128) char a[128];", Space);
- verifyFormat("size_t x = alignof (MyType);", Space);
- verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
- verifyFormat("int f () throw (Deprecated);", Space);
- verifyFormat("typedef void (*cb) (int);", Space);
- verifyFormat("T A::operator() ();", Space);
- verifyFormat("X A::operator++ (T);", Space);
- verifyFormat("auto lambda = [] () { return 0; };", Space);
- verifyFormat("int x = int (y);", Space);
- verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
- verifyFormat("__builtin_LINE ()", Space);
- verifyFormat("__builtin_UNKNOWN ()", Space);
-
- FormatStyle SomeSpace = getLLVMStyle();
- SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
-
- verifyFormat("[]() -> float {}", SomeSpace);
- verifyFormat("[] (auto foo) {}", SomeSpace);
- verifyFormat("[foo]() -> int {}", SomeSpace);
- verifyFormat("int f();", SomeSpace);
- verifyFormat("void f (int a, T b) {\n"
- " while (true)\n"
- " continue;\n"
- "}",
- SomeSpace);
- verifyFormat("if (true)\n"
- " f();\n"
- "else if (true)\n"
- " f();",
- SomeSpace);
- verifyFormat("do {\n"
- " do_something();\n"
- "} while (something());",
- SomeSpace);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- SomeSpace);
- verifyFormat("A::A() : a (1) {}", SomeSpace);
- verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
- verifyFormat("*(&a + 1);\n"
- "&((&a)[1]);\n"
- "a[(b + c) * d];\n"
- "(((a + 1) * 2) + 3) * 4;",
- SomeSpace);
- verifyFormat("#define A(x) x", SomeSpace);
- verifyFormat("#define A (x) x", SomeSpace);
- verifyFormat("#if defined(x)\n"
- "#endif",
- SomeSpace);
- verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
- verifyFormat("size_t x = sizeof (x);", SomeSpace);
- verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
- verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
- verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
- verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
- verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
- verifyFormat("alignas (128) char a[128];", SomeSpace);
- verifyFormat("size_t x = alignof (MyType);", SomeSpace);
- verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
- SomeSpace);
- verifyFormat("int f() throw (Deprecated);", SomeSpace);
- verifyFormat("typedef void (*cb) (int);", SomeSpace);
- verifyFormat("T A::operator()();", SomeSpace);
- verifyFormat("X A::operator++ (T);", SomeSpace);
- verifyFormat("int x = int (y);", SomeSpace);
- verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
-
- FormatStyle SpaceControlStatements = getLLVMStyle();
- SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
-
- verifyFormat("while (true)\n"
- " continue;",
- SpaceControlStatements);
- verifyFormat("if (true)\n"
- " f();\n"
- "else if (true)\n"
- " f();",
- SpaceControlStatements);
- verifyFormat("for (;;) {\n"
- " do_something();\n"
- "}",
- SpaceControlStatements);
- verifyFormat("do {\n"
- " do_something();\n"
- "} while (something());",
- SpaceControlStatements);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- SpaceControlStatements);
-
- FormatStyle SpaceFuncDecl = getLLVMStyle();
- SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
-
- verifyFormat("int f ();", SpaceFuncDecl);
- verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
- verifyFormat("void __attribute__((asdf)) f(int a, T b) {}", SpaceFuncDecl);
- verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
- verifyFormat("template <> void A<C> (C x);", SpaceFuncDecl);
- verifyFormat("template <> void A<C>(C x) {}", SpaceFuncDecl);
- verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
- verifyFormat("void __attribute__((asdf)) f ();", SpaceFuncDecl);
- verifyFormat("#define A(x) x", SpaceFuncDecl);
- verifyFormat("#define A (x) x", SpaceFuncDecl);
- verifyFormat("#if defined(x)\n"
- "#endif",
- SpaceFuncDecl);
- verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
- verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
- verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
- verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
- verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
- verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
- verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
- verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
- verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
- verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
- SpaceFuncDecl);
- verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
- verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
- verifyFormat("T A::operator()();", SpaceFuncDecl);
- verifyFormat("X A::operator++(T);", SpaceFuncDecl);
- verifyFormat("T A::operator()() {}", SpaceFuncDecl);
- verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
- verifyFormat("int x = int(y);", SpaceFuncDecl);
- verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
- SpaceFuncDecl);
-
- FormatStyle SpaceFuncDef = getLLVMStyle();
- SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
-
- verifyFormat("int f();", SpaceFuncDef);
- verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
- verifyFormat("void __attribute__((asdf)) f (int a, T b) {}", SpaceFuncDef);
- verifyFormat("A::A () : a(1) {}", SpaceFuncDef);
- verifyFormat("template <> void A<C>(C x);", SpaceFuncDef);
- verifyFormat("template <> void A<C> (C x) {}", SpaceFuncDef);
- verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
- verifyFormat("void __attribute__((asdf)) f();", SpaceFuncDef);
- verifyFormat("#define A(x) x", SpaceFuncDef);
- verifyFormat("#define A (x) x", SpaceFuncDef);
- verifyFormat("#if defined(x)\n"
- "#endif",
- SpaceFuncDef);
- verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
- verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
- verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
- verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
- verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
- verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
- verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
- verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
- verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
- verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
- SpaceFuncDef);
- verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
- verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
- verifyFormat("T A::operator()();", SpaceFuncDef);
- verifyFormat("X A::operator++(T);", SpaceFuncDef);
- verifyFormat("T A::operator()() {}", SpaceFuncDef);
- verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
- verifyFormat("int x = int(y);", SpaceFuncDef);
- verifyFormat("void foo::bar () {}", SpaceFuncDef);
- verifyFormat("M (std::size_t R, std::size_t C) : C(C), data(R) {}",
- SpaceFuncDef);
-
- FormatStyle SpaceIfMacros = getLLVMStyle();
- SpaceIfMacros.IfMacros.clear();
- SpaceIfMacros.IfMacros.push_back("MYIF");
- SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
- verifyFormat("MYIF (a)\n return;", SpaceIfMacros);
- verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros);
- verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros);
-
- FormatStyle SpaceForeachMacros = getLLVMStyle();
- EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
- FormatStyle::SBS_Never);
- EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
- SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
- verifyFormat("for (;;) {\n"
- "}",
- SpaceForeachMacros);
- verifyFormat("foreach (Item *item, itemlist) {\n"
- "}",
- SpaceForeachMacros);
- verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
- "}",
- SpaceForeachMacros);
- verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
- "}",
- SpaceForeachMacros);
- verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
-
- FormatStyle SomeSpace2 = getLLVMStyle();
- SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
- verifyFormat("[]() -> float {}", SomeSpace2);
- verifyFormat("[] (auto foo) {}", SomeSpace2);
- verifyFormat("[foo]() -> int {}", SomeSpace2);
- verifyFormat("int f();", SomeSpace2);
- verifyFormat("void f (int a, T b) {\n"
- " while (true)\n"
- " continue;\n"
- "}",
- SomeSpace2);
- verifyFormat("if (true)\n"
- " f();\n"
- "else if (true)\n"
- " f();",
- SomeSpace2);
- verifyFormat("do {\n"
- " do_something();\n"
- "} while (something());",
- SomeSpace2);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- SomeSpace2);
- verifyFormat("A::A() : a (1) {}", SomeSpace2);
- verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
- verifyFormat("*(&a + 1);\n"
- "&((&a)[1]);\n"
- "a[(b + c) * d];\n"
- "(((a + 1) * 2) + 3) * 4;",
- SomeSpace2);
- verifyFormat("#define A(x) x", SomeSpace2);
- verifyFormat("#define A (x) x", SomeSpace2);
- verifyFormat("#if defined(x)\n"
- "#endif",
- SomeSpace2);
- verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
- verifyFormat("size_t x = sizeof (x);", SomeSpace2);
- verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
- verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
- verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
- verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
- verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
- verifyFormat("alignas (128) char a[128];", SomeSpace2);
- verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
- verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
- SomeSpace2);
- verifyFormat("int f() throw (Deprecated);", SomeSpace2);
- verifyFormat("typedef void (*cb) (int);", SomeSpace2);
- verifyFormat("T A::operator()();", SomeSpace2);
- verifyFormat("X A::operator++ (T);", SomeSpace2);
- verifyFormat("int x = int (y);", SomeSpace2);
- verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
-
- auto Style = getLLVMStyle();
- Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- EXPECT_FALSE(Style.SpaceBeforeParensOptions.AfterNot);
- Style.SpaceBeforeParensOptions.AfterNot = true;
- verifyFormat("return not (a || b);", Style);
-
- FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
- SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
- .AfterOverloadedOperator = true;
-
- verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
- verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
- verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
- verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
-
- SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
- .AfterOverloadedOperator = false;
-
- verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
- verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
- verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
- verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
-
- auto SpaceAfterRequires = getLLVMStyle();
- SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
- EXPECT_FALSE(
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
- EXPECT_FALSE(
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
- verifyFormat("void f(auto x)\n"
- " requires requires(int i) { x + i; }\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("void f(auto x)\n"
- " requires(requires(int i) { x + i; })\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("if (requires(int i) { x + i; })\n"
- " return;",
- SpaceAfterRequires);
- verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
- verifyFormat("template <typename T>\n"
- " requires(Foo<T>)\n"
- "class Bar;",
- SpaceAfterRequires);
-
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
- verifyFormat("void f(auto x)\n"
- " requires requires(int i) { x + i; }\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("void f(auto x)\n"
- " requires (requires(int i) { x + i; })\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("if (requires(int i) { x + i; })\n"
- " return;",
- SpaceAfterRequires);
- verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
- verifyFormat("template <typename T>\n"
- " requires (Foo<T>)\n"
- "class Bar;",
- SpaceAfterRequires);
-
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
- verifyFormat("void f(auto x)\n"
- " requires requires (int i) { x + i; }\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("void f(auto x)\n"
- " requires(requires (int i) { x + i; })\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("if (requires (int i) { x + i; })\n"
- " return;",
- SpaceAfterRequires);
- verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
- verifyFormat("template <typename T>\n"
- " requires(Foo<T>)\n"
- "class Bar;",
- SpaceAfterRequires);
-
- SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
- verifyFormat("void f(auto x)\n"
- " requires requires (int i) { x + i; }\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("void f(auto x)\n"
- " requires (requires (int i) { x + i; })\n"
- "{}",
- SpaceAfterRequires);
- verifyFormat("if (requires (int i) { x + i; })\n"
- " return;",
- SpaceAfterRequires);
- verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
- verifyFormat("template <typename T>\n"
- " requires (Foo<T>)\n"
- "class Bar;",
- SpaceAfterRequires);
-}
-
-TEST_F(FormatTest, SpaceAfterLogicalNot) {
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpaceAfterLogicalNot = true;
-
- verifyFormat("bool x = ! y", Spaces);
- verifyFormat("if (! isFailure())", Spaces);
- verifyFormat("if (! (a && b))", Spaces);
- verifyFormat("\"Error!\"", Spaces);
- verifyFormat("! ! x", Spaces);
-}
-
-TEST_F(FormatTest, ConfigurableSpacesInParens) {
- FormatStyle Spaces = getLLVMStyle();
-
- verifyFormat("do_something(::globalVar);", Spaces);
- verifyFormat("call(x, y, z);", Spaces);
- verifyFormat("call();", Spaces);
- verifyFormat("std::function<void(int, int)> callback;", Spaces);
- verifyFormat("void inFunction() { std::function<void(int, int)> fct; }",
- Spaces);
- verifyFormat("while ((bool)1)\n"
- " continue;",
- Spaces);
- verifyFormat("for (;;)\n"
- " continue;",
- Spaces);
- verifyFormat("if (true)\n"
- " f();\n"
- "else if (true)\n"
- " f();",
- Spaces);
- verifyFormat("do {\n"
- " do_something((int)i);\n"
- "} while (something());",
- Spaces);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
- verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
- verifyFormat("void f() __attribute__((asdf));", Spaces);
- verifyFormat("x = (int32)y;", Spaces);
- verifyFormat("y = ((int (*)(int))foo)(x);", Spaces);
- verifyFormat("decltype(x) y = 42;", Spaces);
- verifyFormat("decltype((x)) y = z;", Spaces);
- verifyFormat("decltype((foo())) a = foo();", Spaces);
- verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
- verifyFormat("if ((x - y) && (a ^ b))\n"
- " f();",
- Spaces);
- verifyFormat("for (int i = 0; i < 10; i = (i + 1))\n"
- " foo(i);",
- Spaces);
- verifyFormat("switch (x / (y + z)) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
-
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.Other = true;
-
- EXPECT_FALSE(Spaces.SpacesInParensOptions.InConditionalStatements);
- verifyFormat("if (a)\n"
- " return;",
- Spaces);
-
- Spaces.SpacesInParensOptions.InConditionalStatements = true;
- verifyFormat("do_something( ::globalVar );", Spaces);
- verifyFormat("call( x, y, z );", Spaces);
- verifyFormat("call();", Spaces);
- verifyFormat("std::function<void( int, int )> callback;", Spaces);
- verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
- Spaces);
- verifyFormat("while ( (bool)1 )\n"
- " continue;",
- Spaces);
- verifyFormat("for ( ;; )\n"
- " continue;",
- Spaces);
- verifyFormat("if ( true )\n"
- " f();\n"
- "else if ( true )\n"
- " f();",
- Spaces);
- verifyFormat("do {\n"
- " do_something( (int)i );\n"
- "} while ( something() );",
- Spaces);
- verifyFormat("switch ( x ) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
- verifyFormat("SomeType *__attribute__( ( attr ) ) *a = NULL;", Spaces);
- verifyFormat("void __attribute__( ( naked ) ) foo( int bar )", Spaces);
- verifyFormat("void f() __attribute__( ( asdf ) );", Spaces);
- verifyFormat("x = (int32)y;", Spaces);
- verifyFormat("y = ( (int ( * )( int ))foo )( x );", Spaces);
- verifyFormat("decltype( x ) y = 42;", Spaces);
- verifyFormat("decltype( ( x ) ) y = z;", Spaces);
- verifyFormat("decltype( ( foo() ) ) a = foo();", Spaces);
- verifyFormat("decltype( ( bar( 10 ) ) ) a = bar( 11 );", Spaces);
- verifyFormat("if ( ( x - y ) && ( a ^ b ) )\n"
- " f();",
- Spaces);
- verifyFormat("for ( int i = 0; i < 10; i = ( i + 1 ) )\n"
- " foo( i );",
- Spaces);
- verifyFormat("switch ( x / ( y + z ) ) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
-
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.InCStyleCasts = true;
- verifyFormat("Type *A = ( Type * )P;", Spaces);
- verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
- verifyFormat("x = ( int32 )y;", Spaces);
- verifyFormat("throw ( int32 )x;", Spaces);
- verifyFormat("int a = ( int )(2.0f);", Spaces);
- verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
- verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
- verifyFormat("#define x (( int )-1)", Spaces);
- verifyFormat("y = (( int (*)(int) )foo)(x);", Spaces);
-
- // Run the first set of tests again with:
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.InEmptyParentheses = true;
- Spaces.SpacesInParensOptions.InCStyleCasts = true;
- verifyFormat("call(x, y, z);", Spaces);
- verifyFormat("call( );", Spaces);
- verifyFormat("std::function<void(int, int)> callback;", Spaces);
- verifyFormat("while (( bool )1)\n"
- " continue;",
- Spaces);
- verifyFormat("for (;;)\n"
- " continue;",
- Spaces);
- verifyFormat("if (true)\n"
- " f( );\n"
- "else if (true)\n"
- " f( );",
- Spaces);
- verifyFormat("do {\n"
- " do_something(( int )i);\n"
- "} while (something( ));",
- Spaces);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
- verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
- verifyFormat("void f( ) __attribute__((asdf));", Spaces);
- verifyFormat("x = ( int32 )y;", Spaces);
- verifyFormat("y = (( int (*)(int) )foo)(x);", Spaces);
- verifyFormat("decltype(x) y = 42;", Spaces);
- verifyFormat("decltype((x)) y = z;", Spaces);
- verifyFormat("decltype((foo( ))) a = foo( );", Spaces);
- verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
- verifyFormat("if ((x - y) && (a ^ b))\n"
- " f( );",
- Spaces);
- verifyFormat("for (int i = 0; i < 10; i = (i + 1))\n"
- " foo(i);",
- Spaces);
- verifyFormat("switch (x / (y + z)) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
-
- // Run the first set of tests again with:
- Spaces.SpaceAfterCStyleCast = true;
- verifyFormat("call(x, y, z);", Spaces);
- verifyFormat("call( );", Spaces);
- verifyFormat("std::function<void(int, int)> callback;", Spaces);
- verifyFormat("while (( bool ) 1)\n"
- " continue;",
- Spaces);
- verifyFormat("for (;;)\n"
- " continue;",
- Spaces);
- verifyFormat("if (true)\n"
- " f( );\n"
- "else if (true)\n"
- " f( );",
- Spaces);
- verifyFormat("do {\n"
- " do_something(( int ) i);\n"
- "} while (something( ));",
- Spaces);
- verifyFormat("switch (x) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
- verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
- verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
- verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
- verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
- verifyFormat("bool *y = ( bool * ) (x);", Spaces);
- verifyFormat("throw ( int32 ) x;", Spaces);
- verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
- verifyFormat("void f( ) __attribute__((asdf));", Spaces);
-
- // Run subset of tests again with:
- Spaces.SpacesInParensOptions.InCStyleCasts = false;
- Spaces.SpaceAfterCStyleCast = true;
- verifyFormat("while ((bool) 1)\n"
- " continue;",
- Spaces);
- verifyFormat("do {\n"
- " do_something((int) i);\n"
- "} while (something( ));",
- Spaces);
-
- verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
- verifyFormat("size_t idx = (size_t) a;", Spaces);
- verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
- verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
- verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
- verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
- verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
- verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
- verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
- verifyFormat("throw (int32) x;", Spaces);
- verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
- verifyFormat("void f( ) __attribute__((asdf));", Spaces);
-
- Spaces.ColumnLimit = 80;
- Spaces.IndentWidth = 4;
- Spaces.BreakAfterOpenBracketFunction = true;
- verifyFormat("void foo( ) {\n"
- " size_t foo = (*(function))(\n"
- " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
- "BarrrrrrrrrrrrLong,\n"
- " FoooooooooLooooong);\n"
- "}",
- Spaces);
- Spaces.SpaceAfterCStyleCast = false;
- verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
- verifyFormat("size_t idx = (size_t)a;", Spaces);
- verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
- verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
-
- verifyFormat("void foo( ) {\n"
- " size_t foo = (*(function))(\n"
- " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
- "BarrrrrrrrrrrrLong,\n"
- " FoooooooooLooooong);\n"
- "}",
- Spaces);
-
- Spaces.BreakAfterOpenBracketFunction = true;
- Spaces.BreakBeforeCloseBracketFunction = true;
- verifyFormat("void foo( ) {\n"
- " size_t foo = (*(function))(\n"
- " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
- "BarrrrrrrrrrrrLong,\n"
- " FoooooooooLooooong\n"
- " );\n"
- "}",
- Spaces);
- verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
- verifyFormat("size_t idx = (size_t)a;", Spaces);
- verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
- verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
- verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
-
- // Check ExceptDoubleParentheses spaces
- Spaces.IndentWidth = 2;
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.Other = true;
- Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
- verifyFormat("SomeType *__attribute__(( attr )) *a = NULL;", Spaces);
- verifyFormat("void __attribute__(( naked )) foo( int bar )", Spaces);
- verifyFormat("void f() __attribute__(( asdf ));", Spaces);
- verifyFormat("__attribute__(( __aligned__( x ) )) z;", Spaces);
- verifyFormat("int x __attribute__(( aligned( 16 ) )) = 0;", Spaces);
- verifyFormat("class __declspec( dllimport ) X {};", Spaces);
- verifyFormat("class __declspec(( dllimport )) X {};", Spaces);
- verifyFormat("int x = ( ( a - 1 ) * 3 );", Spaces);
- verifyFormat("int x = ( 3 * ( a - 1 ) );", Spaces);
- verifyFormat("decltype( x ) y = 42;", Spaces);
- verifyFormat("decltype(( bar( 10 ) )) a = bar( 11 );", Spaces);
- verifyFormat("if (( i = j ))\n"
- " do_something( i );",
- Spaces);
-
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions = {};
- Spaces.SpacesInParensOptions.InConditionalStatements = true;
- Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
- verifyFormat("while ( (bool)1 )\n"
- " continue;",
- Spaces);
- verifyFormat("while ((i = j))\n"
- " continue;",
- Spaces);
- verifyFormat("do {\n"
- " do_something((int)i);\n"
- "} while ( something() );",
- Spaces);
- verifyFormat("do {\n"
- " do_something((int)i);\n"
- "} while ((i = i + 1));",
- Spaces);
- verifyFormat("if ( (x - y) && (a ^ b) )\n"
- " f();",
- Spaces);
- verifyFormat("if ((i = j))\n"
- " do_something(i);",
- Spaces);
- verifyFormat("for ( int i = 0; i < 10; i = (i + 1) )\n"
- " foo(i);",
- Spaces);
- verifyFormat("switch ( x / (y + z) ) {\n"
- "default:\n"
- " break;\n"
- "}",
- Spaces);
- verifyFormat("if constexpr ((a = b))\n"
- " c;",
- Spaces);
-}
-
-TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
- verifyFormat("int a[5];");
- verifyFormat("a[3] += 42;");
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInSquareBrackets = true;
- // Not lambdas.
- verifyFormat("int a[ 5 ];", Spaces);
- verifyFormat("a[ 3 ] += 42;", Spaces);
- verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
- verifyFormat("double &operator[](int i) { return 0; }\n"
- "int i;",
- Spaces);
- verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
- verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
- verifyFormat("int i = (*b)[ a ]->f();", Spaces);
- // Lambdas.
- verifyFormat("int c = []() -> int { return 2; }();", Spaces);
- verifyFormat("return [ i, args... ] {};", Spaces);
- verifyFormat("int foo = [ &bar ]() {};", Spaces);
- verifyFormat("int foo = [ = ]() {};", Spaces);
- verifyFormat("int foo = [ & ]() {};", Spaces);
- verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
- verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
-}
-
-TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
- FormatStyle NoSpaceStyle = getLLVMStyle();
- verifyFormat("int a[5];", NoSpaceStyle);
- verifyFormat("a[3] += 42;", NoSpaceStyle);
-
- verifyFormat("int a[1];", NoSpaceStyle);
- verifyFormat("int 1 [a];", NoSpaceStyle);
- verifyFormat("int a[1][2];", NoSpaceStyle);
- verifyFormat("a[7] = 5;", NoSpaceStyle);
- verifyFormat("int a = (f())[23];", NoSpaceStyle);
- verifyFormat("f([] {})", NoSpaceStyle);
-
- FormatStyle Space = getLLVMStyle();
- Space.SpaceBeforeSquareBrackets = true;
- verifyFormat("int c = []() -> int { return 2; }();", Space);
- verifyFormat("return [i, args...] {};", Space);
-
- verifyFormat("int a [5];", Space);
- verifyFormat("a [3] += 42;", Space);
- verifyFormat("constexpr char hello []{\"hello\"};", Space);
- verifyFormat("double &operator[](int i) { return 0; }\n"
- "int i;",
- Space);
- verifyFormat("std::unique_ptr<int []> foo() {}", Space);
- verifyFormat("int i = a [a][a]->f();", Space);
- verifyFormat("int i = (*b) [a]->f();", Space);
-
- verifyFormat("int a [1];", Space);
- verifyFormat("int 1 [a];", Space);
- verifyFormat("int a [1][2];", Space);
- verifyFormat("a [7] = 5;", Space);
- verifyFormat("int a = (f()) [23];", Space);
- verifyFormat("f([] {})", Space);
-}
-
-TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
- verifyFormat("int a = 5;");
- verifyFormat("a += 42;");
- verifyFormat("a or_eq 8;");
-
- auto Spaces = getLLVMStyle(FormatStyle::LK_C);
- verifyFormat("xor = foo;", Spaces);
-
- Spaces.Language = FormatStyle::LK_Cpp;
- Spaces.SpaceBeforeAssignmentOperators = false;
- verifyFormat("int a= 5;", Spaces);
- verifyFormat("a+= 42;", Spaces);
- verifyFormat("a or_eq 8;", Spaces);
- verifyFormat("xor= foo;", Spaces);
-}
-
-TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
- verifyFormat("class Foo : public Bar {};");
- verifyFormat("Foo::Foo() : foo(1) {}");
- verifyFormat("for (auto a : b) {\n}");
- verifyFormat("int x = a ? b : c;");
- verifyFormat("{\n"
- "label0:\n"
- " int x = 0;\n"
- "}");
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- "default:\n"
- "}");
- verifyFormat("switch (allBraces) {\n"
- "case 1: {\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default: {\n"
- " break;\n"
- "}\n"
- "}");
-
- FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
- CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
- verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
- verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
- verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
- verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
- verifyFormat("{\n"
- "label1:\n"
- " int x = 0;\n"
- "}",
- CtorInitializerStyle);
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- "default:\n"
- "}",
- CtorInitializerStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1: {\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default: {\n"
- " break;\n"
- "}\n"
- "}",
- CtorInitializerStyle);
- CtorInitializerStyle.BreakConstructorInitializers =
- FormatStyle::BCIS_AfterColon;
- verifyFormat("Fooooooooooo::Fooooooooooo():\n"
- " aaaaaaaaaaaaaaaa(1),\n"
- " bbbbbbbbbbbbbbbb(2) {}",
- CtorInitializerStyle);
- CtorInitializerStyle.BreakConstructorInitializers =
- FormatStyle::BCIS_BeforeComma;
- verifyFormat("Fooooooooooo::Fooooooooooo()\n"
- " : aaaaaaaaaaaaaaaa(1)\n"
- " , bbbbbbbbbbbbbbbb(2) {}",
- CtorInitializerStyle);
- CtorInitializerStyle.BreakConstructorInitializers =
- FormatStyle::BCIS_BeforeColon;
- verifyFormat("Fooooooooooo::Fooooooooooo()\n"
- " : aaaaaaaaaaaaaaaa(1),\n"
- " bbbbbbbbbbbbbbbb(2) {}",
- CtorInitializerStyle);
- CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
- verifyFormat("Fooooooooooo::Fooooooooooo()\n"
- ": aaaaaaaaaaaaaaaa(1),\n"
- " bbbbbbbbbbbbbbbb(2) {}",
- CtorInitializerStyle);
-
- FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
- InheritanceStyle.SpaceBeforeInheritanceColon = false;
- verifyFormat("class Foo: public Bar {};", InheritanceStyle);
- verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
- verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
- verifyFormat("int x = a ? b : c;", InheritanceStyle);
- verifyFormat("{\n"
- "label2:\n"
- " int x = 0;\n"
- "}",
- InheritanceStyle);
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- "default:\n"
- "}",
- InheritanceStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1: {\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default: {\n"
- " break;\n"
- "}\n"
- "}",
- InheritanceStyle);
- InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
- verifyFormat("class Foooooooooooooooooooooo\n"
- " : public aaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbb {\n"
- "}",
- InheritanceStyle);
- InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
- verifyFormat("class Foooooooooooooooooooooo:\n"
- " public aaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbb {\n"
- "}",
- InheritanceStyle);
- InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
- verifyFormat("class Foooooooooooooooooooooo\n"
- " : public aaaaaaaaaaaaaaaaaa\n"
- " , public bbbbbbbbbbbbbbbbbb {\n"
- "}",
- InheritanceStyle);
- InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
- verifyFormat("class Foooooooooooooooooooooo\n"
- " : public aaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbb {\n"
- "}",
- InheritanceStyle);
- InheritanceStyle.ConstructorInitializerIndentWidth = 0;
- verifyFormat("class Foooooooooooooooooooooo\n"
- ": public aaaaaaaaaaaaaaaaaa,\n"
- " public bbbbbbbbbbbbbbbbbb {}",
- InheritanceStyle);
-
- FormatStyle ForLoopStyle = getLLVMStyle();
- ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
- verifyFormat("class Foo : public Bar {};", ForLoopStyle);
- verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
- verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
- verifyFormat("int x = a ? b : c;", ForLoopStyle);
- verifyFormat("{\n"
- "label2:\n"
- " int x = 0;\n"
- "}",
- ForLoopStyle);
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- "default:\n"
- "}",
- ForLoopStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1: {\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default: {\n"
- " break;\n"
- "}\n"
- "}",
- ForLoopStyle);
-
- FormatStyle CaseStyle = getLLVMStyle();
- CaseStyle.SpaceBeforeCaseColon = true;
- verifyFormat("class Foo : public Bar {};", CaseStyle);
- verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
- verifyFormat("for (auto a : b) {\n}", CaseStyle);
- verifyFormat("int x = a ? b : c;", CaseStyle);
- verifyFormat("switch (x) {\n"
- "case 1 :\n"
- "default :\n"
- "}",
- CaseStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1 : {\n"
- " break;\n"
- "}\n"
- "case 2 : {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default : {\n"
- " break;\n"
- "}\n"
- "}",
- CaseStyle);
- // Goto labels should not be affected.
- verifyFormat("switch (x) {\n"
- "goto_label:\n"
- "default :\n"
- "}",
- CaseStyle);
- verifyFormat("switch (x) {\n"
- "goto_label: { break; }\n"
- "default : {\n"
- " break;\n"
- "}\n"
- "}",
- CaseStyle);
-
- FormatStyle NoSpaceStyle = getLLVMStyle();
- EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
- NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
- NoSpaceStyle.SpaceBeforeInheritanceColon = false;
- NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
- verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
- verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
- verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
- verifyFormat("int x = a ? b : c;", NoSpaceStyle);
- verifyFormat("{\n"
- "label3:\n"
- " int x = 0;\n"
- "}",
- NoSpaceStyle);
- verifyFormat("switch (x) {\n"
- "case 1:\n"
- "default:\n"
- "}",
- NoSpaceStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1: {\n"
- " break;\n"
- "}\n"
- "case 2: {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default: {\n"
- " break;\n"
- "}\n"
- "}",
- NoSpaceStyle);
-
- FormatStyle InvertedSpaceStyle = getLLVMStyle();
- InvertedSpaceStyle.SpaceBeforeCaseColon = true;
- InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
- InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
- InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
- verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
- verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
- verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
- verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
- verifyFormat("{\n"
- "label3:\n"
- " int x = 0;\n"
- "}",
- InvertedSpaceStyle);
- verifyFormat("switch (x) {\n"
- "case 1 :\n"
- "case 2 : {\n"
- " break;\n"
- "}\n"
- "default :\n"
- " break;\n"
- "}",
- InvertedSpaceStyle);
- verifyFormat("switch (allBraces) {\n"
- "case 1 : {\n"
- " break;\n"
- "}\n"
- "case 2 : {\n"
- " [[fallthrough]];\n"
- "}\n"
- "default : {\n"
- " break;\n"
- "}\n"
- "}",
- InvertedSpaceStyle);
-}
-
-TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
- FormatStyle Style = getLLVMStyle();
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
- verifyFormat("void* const* x = NULL;", Style);
-
-#define verifyQualifierSpaces(Code, Pointers, Qualifiers) \
- do { \
- Style.PointerAlignment = FormatStyle::Pointers; \
- Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \
- verifyFormat(Code, Style); \
- } while (false)
-
- verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
- verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
- verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
-
- verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
- verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
- verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
-
- verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
- verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
- verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
-
- verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
- verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
- verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
-
- verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
- SAPQ_Default);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
- SAPQ_Default);
-
- verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
- SAPQ_Before);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
- SAPQ_Before);
-
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
- SAPQ_After);
-
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
- verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
-
-#undef verifyQualifierSpaces
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.AttributeMacros.push_back("qualified");
- Spaces.PointerAlignment = FormatStyle::PAS_Right;
- Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
- verifyFormat("SomeType *volatile *a = NULL;", Spaces);
- verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("std::vector<SomeType *const *> x;", Spaces);
- verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
- verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
- Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
- verifyFormat("SomeType * volatile *a = NULL;", Spaces);
- verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
- verifyFormat("std::vector<SomeType * const *> x;", Spaces);
- verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
- verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
-
- // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
- Spaces.PointerAlignment = FormatStyle::PAS_Left;
- Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
- verifyFormat("SomeType* volatile* a = NULL;", Spaces);
- verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
- verifyFormat("std::vector<SomeType* const*> x;", Spaces);
- verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
- verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
- // However, setting it to SAPQ_After should add spaces after __attribute, etc.
- Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
- verifyFormat("SomeType* volatile * a = NULL;", Spaces);
- verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
- verifyFormat("std::vector<SomeType* const *> x;", Spaces);
- verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
- verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
-
- // PAS_Middle should not have any noticeable changes even for SAPQ_Both
- Spaces.PointerAlignment = FormatStyle::PAS_Middle;
- Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
- verifyFormat("SomeType * volatile * a = NULL;", Spaces);
- verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
- verifyFormat("std::vector<SomeType * const *> x;", Spaces);
- verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
- verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
-}
-
-TEST_F(FormatTest, LinuxBraceBreaking) {
- FormatStyle LinuxBraceStyle = getLLVMStyle();
- LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
- verifyFormat("namespace a\n"
- "{\n"
- "class A\n"
- "{\n"
- " void f()\n"
- " {\n"
- " if (true) {\n"
- " a();\n"
- " b();\n"
- " } else {\n"
- " a();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "};\n"
- "struct B {\n"
- " int x;\n"
- "};\n"
- "} // namespace a",
- LinuxBraceStyle);
- verifyFormat("enum X {\n"
- " Y = 0,\n"
- "}",
- LinuxBraceStyle);
- verifyFormat("struct S {\n"
- " int Type;\n"
- " union {\n"
- " int x;\n"
- " double y;\n"
- " } Value;\n"
- " class C\n"
- " {\n"
- " MyFavoriteType Value;\n"
- " } Class;\n"
- "}",
- LinuxBraceStyle);
-}
-
-TEST_F(FormatTest, MozillaBraceBreaking) {
- FormatStyle MozillaBraceStyle = getLLVMStyle();
- MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
- MozillaBraceStyle.FixNamespaceComments = false;
- verifyFormat("namespace a {\n"
- "class A\n"
- "{\n"
- " void f()\n"
- " {\n"
- " if (true) {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "};\n"
- "enum E\n"
- "{\n"
- " A,\n"
- " // foo\n"
- " B,\n"
- " C\n"
- "};\n"
- "struct B\n"
- "{\n"
- " int x;\n"
- "};\n"
- "}",
- MozillaBraceStyle);
- verifyFormat("struct S\n"
- "{\n"
- " int Type;\n"
- " union\n"
- " {\n"
- " int x;\n"
- " double y;\n"
- " } Value;\n"
- " class C\n"
- " {\n"
- " MyFavoriteType Value;\n"
- " } Class;\n"
- "}",
- MozillaBraceStyle);
-}
-
-TEST_F(FormatTest, StroustrupBraceBreaking) {
- FormatStyle StroustrupBraceStyle = getLLVMStyle();
- StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
- verifyFormat("namespace a {\n"
- "class A {\n"
- " void f()\n"
- " {\n"
- " if (true) {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "};\n"
- "struct B {\n"
- " int x;\n"
- "};\n"
- "} // namespace a",
- StroustrupBraceStyle);
-
- verifyFormat("void foo()\n"
- "{\n"
- " if (a) {\n"
- " a();\n"
- " }\n"
- " else {\n"
- " b();\n"
- " }\n"
- "}",
- StroustrupBraceStyle);
-
- verifyFormat("#ifdef _DEBUG\n"
- "int foo(int i = 0)\n"
- "#else\n"
- "int foo(int i = 5)\n"
- "#endif\n"
- "{\n"
- " return i;\n"
- "}",
- StroustrupBraceStyle);
-
- verifyFormat("void foo() {}\n"
- "void bar()\n"
- "#ifdef _DEBUG\n"
- "{\n"
- " foo();\n"
- "}\n"
- "#else\n"
- "{\n"
- "}\n"
- "#endif",
- StroustrupBraceStyle);
-
- verifyFormat("void foobar() { int i = 5; }\n"
- "#ifdef _DEBUG\n"
- "void bar() {}\n"
- "#else\n"
- "void bar() { foobar(); }\n"
- "#endif",
- StroustrupBraceStyle);
-}
-
-TEST_F(FormatTest, AllmanBraceBreaking) {
- FormatStyle AllmanBraceStyle = getLLVMStyle();
- AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
-
- verifyFormat("namespace a\n"
- "{\n"
- "void f();\n"
- "void g();\n"
- "} // namespace a",
- "namespace a\n"
- "{\n"
- "void f();\n"
- "void g();\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("namespace a\n"
- "{\n"
- "class A\n"
- "{\n"
- " void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "};\n"
- "struct B\n"
- "{\n"
- " int x;\n"
- "};\n"
- "union C\n"
- "{\n"
- "};\n"
- "} // namespace a",
- AllmanBraceStyle);
-
- verifyFormat("void f()\n"
- "{\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " }\n"
- " else if (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " else\n"
- " {\n"
- " c();\n"
- " }\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("void f()\n"
- "{\n"
- " for (int i = 0; i < 10; ++i)\n"
- " {\n"
- " a();\n"
- " }\n"
- " while (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " do\n"
- " {\n"
- " c();\n"
- " } while (false)\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("void f(int a)\n"
- "{\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " break;\n"
- " case 1:\n"
- " {\n"
- " break;\n"
- " }\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " default:\n"
- " break;\n"
- " }\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("enum X\n"
- "{\n"
- " Y = 0,\n"
- "}",
- AllmanBraceStyle);
- verifyFormat("enum X\n"
- "{\n"
- " Y = 0\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("@interface BSApplicationController ()\n"
- "{\n"
- "@private\n"
- " id _extraIvar;\n"
- "}\n"
- "@end",
- AllmanBraceStyle);
-
- verifyFormat("#ifdef _DEBUG\n"
- "int foo(int i = 0)\n"
- "#else\n"
- "int foo(int i = 5)\n"
- "#endif\n"
- "{\n"
- " return i;\n"
- "}",
- AllmanBraceStyle);
-
- verifyFormat("void foo() {}\n"
- "void bar()\n"
- "#ifdef _DEBUG\n"
- "{\n"
- " foo();\n"
- "}\n"
- "#else\n"
- "{\n"
- "}\n"
- "#endif",
- AllmanBraceStyle);
-
- verifyFormat("void foobar() { int i = 5; }\n"
- "#ifdef _DEBUG\n"
- "void bar() {}\n"
- "#else\n"
- "void bar() { foobar(); }\n"
- "#endif",
- AllmanBraceStyle);
-
- EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
- FormatStyle::SLS_All);
-
- verifyFormat("[](int i) { return i + 2; };\n"
- "[](int i, int j)\n"
- "{\n"
- " auto x = i + j;\n"
- " auto y = i * j;\n"
- " return x ^ y;\n"
- "};\n"
- "void foo()\n"
- "{\n"
- " auto shortLambda = [](int i) { return i + 2; };\n"
- " auto longLambda = [](int i, int j)\n"
- " {\n"
- " auto x = i + j;\n"
- " auto y = i * j;\n"
- " return x ^ y;\n"
- " };\n"
- "}",
- AllmanBraceStyle);
-
- AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
-
- verifyFormat("[](int i)\n"
- "{\n"
- " return i + 2;\n"
- "};\n"
- "[](int i, int j)\n"
- "{\n"
- " auto x = i + j;\n"
- " auto y = i * j;\n"
- " return x ^ y;\n"
- "};\n"
- "void foo()\n"
- "{\n"
- " auto shortLambda = [](int i)\n"
- " {\n"
- " return i + 2;\n"
- " };\n"
- " auto longLambda = [](int i, int j)\n"
- " {\n"
- " auto x = i + j;\n"
- " auto y = i * j;\n"
- " return x ^ y;\n"
- " };\n"
- "}",
- AllmanBraceStyle);
-
- // Reset
- AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
-
- // This shouldn't affect ObjC blocks..
- verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
- " // ...\n"
- " int i;\n"
- "}];",
- AllmanBraceStyle);
- verifyFormat("void (^block)(void) = ^{\n"
- " // ...\n"
- " int i;\n"
- "};",
- AllmanBraceStyle);
- // .. or dict literals.
- verifyFormat("void f()\n"
- "{\n"
- " // ...\n"
- " [object someMethod:@{@\"a\" : @\"b\"}];\n"
- "}",
- AllmanBraceStyle);
- verifyFormat("void f()\n"
- "{\n"
- " // ...\n"
- " [object someMethod:@{a : @\"b\"}];\n"
- "}",
- AllmanBraceStyle);
- verifyFormat("int f()\n"
- "{ // comment\n"
- " return 42;\n"
- "}",
- AllmanBraceStyle);
-
- AllmanBraceStyle.ColumnLimit = 19;
- verifyFormat("void f() { int i; }", AllmanBraceStyle);
- AllmanBraceStyle.ColumnLimit = 18;
- verifyFormat("void f()\n"
- "{\n"
- " int i;\n"
- "}",
- AllmanBraceStyle);
- AllmanBraceStyle.ColumnLimit = 80;
-
- FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
- BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_WithoutElse;
- BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if constexpr (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if CONSTEXPR (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if (b) return;\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if constexpr (b) return;\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " if CONSTEXPR (b) return;\n"
- "}",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- "{\n"
- " while (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- "}",
- BreakBeforeBraceShortIfs);
-}
-
-TEST_F(FormatTest, WhitesmithsBraceBreaking) {
- FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
- WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
-
- // Make a few changes to the style for testing purposes
- WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setEmptyOnly();
- WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
-
- // FIXME: this test case can't decide whether there should be a blank line
- // after the ~D() line or not. It adds one if one doesn't exist in the test
- // and it removes the line if one exists.
- /*
- verifyFormat("class A;\n"
- "namespace B\n"
- " {\n"
- "class C;\n"
- "// Comment\n"
- "class D\n"
- " {\n"
- "public:\n"
- " D();\n"
- " ~D() {}\n"
- "private:\n"
- " enum E\n"
- " {\n"
- " F\n"
- " }\n"
- " };\n"
- " } // namespace B",
- WhitesmithsBraceStyle);
- */
-
- WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
- verifyFormat("namespace a\n"
- " {\n"
- "class A\n"
- " {\n"
- " void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g()\n"
- " {\n"
- " return;\n"
- " }\n"
- " };\n"
- "struct B\n"
- " {\n"
- " int x;\n"
- " };\n"
- " } // namespace a",
- WhitesmithsBraceStyle);
-
- verifyFormat("namespace a\n"
- " {\n"
- "namespace b\n"
- " {\n"
- "class A\n"
- " {\n"
- " void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g()\n"
- " {\n"
- " return;\n"
- " }\n"
- " };\n"
- "struct B\n"
- " {\n"
- " int x;\n"
- " };\n"
- " } // namespace b\n"
- " } // namespace a",
- WhitesmithsBraceStyle);
-
- WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
- verifyFormat("namespace a\n"
- " {\n"
- "namespace b\n"
- " {\n"
- " class A\n"
- " {\n"
- " void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g()\n"
- " {\n"
- " return;\n"
- " }\n"
- " };\n"
- " struct B\n"
- " {\n"
- " int x;\n"
- " };\n"
- " } // namespace b\n"
- " } // namespace a",
- WhitesmithsBraceStyle);
-
- WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
- verifyFormat("namespace a\n"
- " {\n"
- " namespace b\n"
- " {\n"
- " class A\n"
- " {\n"
- " void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g()\n"
- " {\n"
- " return;\n"
- " }\n"
- " };\n"
- " struct B\n"
- " {\n"
- " int x;\n"
- " };\n"
- " } // namespace b\n"
- " } // namespace a",
- WhitesmithsBraceStyle);
-
- verifyFormat("void f()\n"
- " {\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " }\n"
- " else if (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " else\n"
- " {\n"
- " c();\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void f()\n"
- " {\n"
- " for (int i = 0; i < 10; ++i)\n"
- " {\n"
- " a();\n"
- " }\n"
- " while (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " do\n"
- " {\n"
- " c();\n"
- " } while (false)\n"
- " }",
- WhitesmithsBraceStyle);
-
- WhitesmithsBraceStyle.IndentCaseLabels = true;
- verifyFormat("void switchTest1(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void switchTest2(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " break;\n"
- " case 1:\n"
- " {\n"
- " break;\n"
- " }\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " default:\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void switchTest3(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " {\n"
- " foo(x);\n"
- " }\n"
- " break;\n"
- " default:\n"
- " {\n"
- " foo(1);\n"
- " }\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- WhitesmithsBraceStyle.IndentCaseLabels = false;
-
- verifyFormat("void switchTest4(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void switchTest5(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " break;\n"
- " case 1:\n"
- " {\n"
- " foo();\n"
- " break;\n"
- " }\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " default:\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void switchTest6(int a)\n"
- " {\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " {\n"
- " foo(x);\n"
- " }\n"
- " break;\n"
- " default:\n"
- " {\n"
- " foo(1);\n"
- " }\n"
- " break;\n"
- " }\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("enum X\n"
- " {\n"
- " Y = 0, // testing\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("enum X\n"
- " {\n"
- " Y = 0\n"
- " }",
- WhitesmithsBraceStyle);
- verifyFormat("enum X\n"
- " {\n"
- " Y = 0,\n"
- " Z = 1\n"
- " };\n"
- "int i;",
- WhitesmithsBraceStyle);
-
- verifyFormat("@interface BSApplicationController ()\n"
- " {\n"
- "@private\n"
- " id _extraIvar;\n"
- " }\n"
- "@end",
- WhitesmithsBraceStyle);
-
- verifyFormat("#ifdef _DEBUG\n"
- "int foo(int i = 0)\n"
- "#else\n"
- "int foo(int i = 5)\n"
- "#endif\n"
- " {\n"
- " return i;\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("void foo() {}\n"
- "void bar()\n"
- "#ifdef _DEBUG\n"
- " {\n"
- " foo();\n"
- " }\n"
- "#else\n"
- " {\n"
- " }\n"
- "#endif",
- WhitesmithsBraceStyle);
-
- verifyFormat("void foobar()\n"
- " {\n"
- " int i = 5;\n"
- " }\n"
- "#ifdef _DEBUG\n"
- "void bar() {}\n"
- "#else\n"
- "void bar()\n"
- " {\n"
- " foobar();\n"
- " }\n"
- "#endif",
- WhitesmithsBraceStyle);
-
- // This shouldn't affect ObjC blocks..
- verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
- " // ...\n"
- " int i;\n"
- "}];",
- WhitesmithsBraceStyle);
- verifyFormat("void (^block)(void) = ^{\n"
- " // ...\n"
- " int i;\n"
- "};",
- WhitesmithsBraceStyle);
- // .. or dict literals.
- verifyFormat("void f()\n"
- " {\n"
- " [object someMethod:@{@\"a\" : @\"b\"}];\n"
- " }",
- WhitesmithsBraceStyle);
-
- verifyFormat("int f()\n"
- " { // comment\n"
- " return 42;\n"
- " }",
- WhitesmithsBraceStyle);
-
- FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
- BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
- FormatStyle::SIS_OnlyFirstIf;
- BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
- verifyFormat("void f(bool b)\n"
- " {\n"
- " if (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- " }",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- " {\n"
- " if (b) return;\n"
- " }",
- BreakBeforeBraceShortIfs);
- verifyFormat("void f(bool b)\n"
- " {\n"
- " while (b)\n"
- " {\n"
- " return;\n"
- " }\n"
- " }",
- BreakBeforeBraceShortIfs);
-}
-
-TEST_F(FormatTest, GNUBraceBreaking) {
- FormatStyle GNUBraceStyle = getLLVMStyle();
- GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
- verifyFormat("namespace a\n"
- "{\n"
- "class A\n"
- "{\n"
- " void f()\n"
- " {\n"
- " int a;\n"
- " {\n"
- " int b;\n"
- " }\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "}\n"
- "} // namespace a",
- GNUBraceStyle);
-
- verifyFormat("void f()\n"
- "{\n"
- " if (true)\n"
- " {\n"
- " a();\n"
- " }\n"
- " else if (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " else\n"
- " {\n"
- " c();\n"
- " }\n"
- "}",
- GNUBraceStyle);
-
- verifyFormat("void f()\n"
- "{\n"
- " for (int i = 0; i < 10; ++i)\n"
- " {\n"
- " a();\n"
- " }\n"
- " while (false)\n"
- " {\n"
- " b();\n"
- " }\n"
- " do\n"
- " {\n"
- " c();\n"
- " }\n"
- " while (false);\n"
- "}",
- GNUBraceStyle);
-
- verifyFormat("void f(int a)\n"
- "{\n"
- " switch (a)\n"
- " {\n"
- " case 0:\n"
- " break;\n"
- " case 1:\n"
- " {\n"
- " break;\n"
- " }\n"
- " case 2:\n"
- " {\n"
- " }\n"
- " break;\n"
- " default:\n"
- " break;\n"
- " }\n"
- "}",
- GNUBraceStyle);
-
- verifyFormat("enum X\n"
- "{\n"
- " Y = 0,\n"
- "}",
- GNUBraceStyle);
-
- verifyFormat("@interface BSApplicationController ()\n"
- "{\n"
- "@private\n"
- " id _extraIvar;\n"
- "}\n"
- "@end",
- GNUBraceStyle);
-
- verifyFormat("#ifdef _DEBUG\n"
- "int foo(int i = 0)\n"
- "#else\n"
- "int foo(int i = 5)\n"
- "#endif\n"
- "{\n"
- " return i;\n"
- "}",
- GNUBraceStyle);
-
- verifyFormat("void foo() {}\n"
- "void bar()\n"
- "#ifdef _DEBUG\n"
- "{\n"
- " foo();\n"
- "}\n"
- "#else\n"
- "{\n"
- "}\n"
- "#endif",
- GNUBraceStyle);
-
- verifyFormat("void foobar() { int i = 5; }\n"
- "#ifdef _DEBUG\n"
- "void bar() {}\n"
- "#else\n"
- "void bar() { foobar(); }\n"
- "#endif",
- GNUBraceStyle);
-}
-
-TEST_F(FormatTest, WebKitBraceBreaking) {
- FormatStyle WebKitBraceStyle = getLLVMStyle();
- WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
- WebKitBraceStyle.FixNamespaceComments = false;
- verifyFormat("namespace a {\n"
- "class A {\n"
- " void f()\n"
- " {\n"
- " if (true) {\n"
- " a();\n"
- " b();\n"
- " }\n"
- " }\n"
- " void g() { return; }\n"
- "};\n"
- "enum E {\n"
- " A,\n"
- " // foo\n"
- " B,\n"
- " C\n"
- "};\n"
- "struct B {\n"
- " int x;\n"
- "};\n"
- "}",
- WebKitBraceStyle);
- verifyFormat("struct S {\n"
- " int Type;\n"
- " union {\n"
- " int x;\n"
- " double y;\n"
- " } Value;\n"
- " class C {\n"
- " MyFavoriteType Value;\n"
- " } Class;\n"
- "};",
- WebKitBraceStyle);
-}
-
-TEST_F(FormatTest, CatchExceptionReferenceBinding) {
- verifyFormat("void f() {\n"
- " try {\n"
- " } catch (const Exception &e) {\n"
- " }\n"
- "}");
-}
-
-TEST_F(FormatTest, UnderstandsPragmas) {
- verifyFormat("#pragma omp reduction(| : var)");
- verifyFormat("#pragma omp reduction(+ : var)");
-
- verifyFormat("#pragma mark Any non-hyphenated or hyphenated string "
- "(including parentheses).",
- "#pragma mark Any non-hyphenated or hyphenated string "
- "(including parentheses).");
-
- verifyFormat("#pragma mark Any non-hyphenated or hyphenated string "
- "(including parentheses).",
- "#pragma mark Any non-hyphenated or hyphenated string "
- "(including parentheses).");
-
- verifyFormat("#pragma comment(linker, \\\n"
- " \"argument\" \\\n"
- " \"argument\"",
- "#pragma comment(linker, \\\n"
- " \"argument\" \\\n"
- " \"argument\"",
- getStyleWithColumns(getChromiumStyle(FormatStyle::LK_Cpp), 32));
-}
-
-TEST_F(FormatTest, UnderstandsPragmaOmpTarget) {
- verifyFormat("#pragma omp target map(to : var)");
- verifyFormat("#pragma omp target map(to : var[ : N])");
- verifyFormat("#pragma omp target map(to : var[0 : N])");
- verifyFormat("#pragma omp target map(always, to : var[0 : N])");
-
- verifyFormat(
- "#pragma omp target \\\n"
- " reduction(+ : var) \\\n"
- " map(to : A[0 : N]) \\\n"
- " map(to : B[0 : N]) \\\n"
- " map(from : C[0 : N]) \\\n"
- " firstprivate(i) \\\n"
- " firstprivate(j) \\\n"
- " firstprivate(k)",
- "#pragma omp target reduction(+:var) map(to:A[0:N]) map(to:B[0:N]) "
- "map(from:C[0:N]) firstprivate(i) firstprivate(j) firstprivate(k)",
- getLLVMStyleWithColumns(26));
-}
-
-TEST_F(FormatTest, UnderstandPragmaOption) {
- verifyFormat("#pragma option -C -A");
-
- verifyFormat("#pragma option -C -A", "#pragma option -C -A");
-}
-
-TEST_F(FormatTest, UnderstandPragmaRegion) {
- auto Style = getLLVMStyleWithColumns(0);
- verifyFormat("#pragma region TEST(FOO : BAR)", Style);
- verifyFormat("#pragma region TEST(FOO: NOSPACE)", Style);
-}
-
-TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
- FormatStyle Style = getLLVMStyleWithColumns(20);
-
- // See PR41213
- verifyFormat("/*\n"
- " *\t9012345\n"
- " * /8901\n"
- " */",
- "/*\n"
- " *\t9012345 /8901\n"
- " */",
- Style);
- verifyFormat("/*\n"
- " *345678\n"
- " *\t/8901\n"
- " */",
- "/*\n"
- " *345678\t/8901\n"
- " */",
- Style);
-
- verifyFormat("int a; // the\n"
- " // comment",
- Style);
- verifyNoChange("int a; /* first line\n"
- " * second\n"
- " * line third\n"
- " * line\n"
- " */",
- Style);
- verifyFormat("int a; // first line\n"
- " // second\n"
- " // line third\n"
- " // line",
- "int a; // first line\n"
- " // second line\n"
- " // third line",
- Style);
-
- Style.PenaltyExcessCharacter = 90;
- verifyFormat("int a; // the comment", Style);
- verifyFormat("int a; // the comment\n"
- " // aaa",
- "int a; // the comment aaa", Style);
- verifyNoChange("int a; /* first line\n"
- " * second line\n"
- " * third line\n"
- " */",
- Style);
- verifyFormat("int a; // first line\n"
- " // second line\n"
- " // third line",
- Style);
- // FIXME: Investigate why this is not getting the same layout as the test
- // above.
- verifyFormat("int a; /* first line\n"
- " * second line\n"
- " * third line\n"
- " */",
- "int a; /* first line second line third line"
- "\n*/",
- Style);
-
- verifyFormat("// foo bar baz bazfoo\n"
- "// foo bar foo bar",
- "// foo bar baz bazfoo\n"
- "// foo bar foo bar",
- Style);
- verifyFormat("// foo bar baz bazfoo\n"
- "// foo bar foo bar",
- "// foo bar baz bazfoo\n"
- "// foo bar foo bar",
- Style);
-
- // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
- // next one.
- verifyFormat("// foo bar baz bazfoo\n"
- "// bar foo bar",
- "// foo bar baz bazfoo bar\n"
- "// foo bar",
- Style);
-
- // FIXME: unstable test case
- EXPECT_EQ("// foo bar baz bazfoo\n"
- "// foo bar baz bazfoo\n"
- "// bar foo bar",
- format("// foo bar baz bazfoo\n"
- "// foo bar baz bazfoo bar\n"
- "// foo bar",
- Style));
-
- // FIXME: unstable test case
- EXPECT_EQ("// foo bar baz bazfoo\n"
- "// foo bar baz bazfoo\n"
- "// bar foo bar",
- format("// foo bar baz bazfoo\n"
- "// foo bar baz bazfoo bar\n"
- "// foo bar",
- Style));
-
- // Make sure we do not keep protruding characters if strict mode reflow is
- // cheaper than keeping protruding characters.
- Style.ColumnLimit = 21;
- verifyFormat("// foo foo foo foo\n"
- "// foo foo foo foo\n"
- "// foo foo foo foo",
- "// foo foo foo foo foo foo foo foo foo foo foo foo", Style);
-
- verifyFormat("int a = /* long block\n"
- " comment */\n"
- " 42;",
- "int a = /* long block comment */ 42;", Style);
-}
-
-TEST_F(FormatTest, BreakPenaltyAfterLParen) {
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 8;
- Style.PenaltyExcessCharacter = 15;
- verifyFormat("int foo(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
- Style.PenaltyBreakOpenParenthesis = 200;
- verifyFormat("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
- "int foo(\n"
- " int aaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
-}
-
-TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 5;
- Style.PenaltyExcessCharacter = 150;
- verifyFormat("foo((\n"
- " int)aaaaaaaaaaaaaaaaaaaaaaaa);",
-
- Style);
- Style.PenaltyBreakOpenParenthesis = 100'000;
- verifyFormat("foo((int)\n"
- " aaaaaaaaaaaaaaaaaaaaaaaa);",
- "foo((\n"
- "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
-}
-
-TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 4;
- Style.PenaltyExcessCharacter = 100;
- verifyFormat("for (\n"
- " int iiiiiiiiiiiiiiiii =\n"
- " 0;\n"
- " iiiiiiiiiiiiiiiii <\n"
- " 2;\n"
- " iiiiiiiiiiiiiiiii++) {\n"
- "}",
-
- Style);
- Style.PenaltyBreakOpenParenthesis = 1250;
- verifyFormat("for (int iiiiiiiiiiiiiiiii =\n"
- " 0;\n"
- " iiiiiiiiiiiiiiiii <\n"
- " 2;\n"
- " iiiiiiiiiiiiiiiii++) {\n"
- "}",
- "for (\n"
- " int iiiiiiiiiiiiiiiii =\n"
- " 0;\n"
- " iiiiiiiiiiiiiiiii <\n"
- " 2;\n"
- " iiiiiiiiiiiiiiiii++) {\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, BreakPenaltyBeforeMemberAccess) {
- auto Style = getLLVMStyle();
- EXPECT_EQ(Style.PenaltyBreakBeforeMemberAccess, 150u);
-
- Style.ColumnLimit = 60;
- Style.PenaltyBreakBeforeMemberAccess = 110;
- verifyFormat("aaaaaaaa.aaaaaaaa.bbbbbbbb()\n"
- " .ccccccccccccccccccccc(dddddddd);\n"
- "aaaaaaaa.aaaaaaaa\n"
- " .bbbbbbbb(cccccccccccccccccccccccccccccccc);",
- Style);
-
- Style.ColumnLimit = 13;
- verifyFormat("foo->bar\n"
- " .b(a);",
- Style);
-}
-
-TEST_F(FormatTest, BreakPenaltyScopeResolution) {
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 20;
- Style.PenaltyExcessCharacter = 100;
- verifyFormat("unsigned long\n"
- "foo::bar();",
- Style);
- Style.PenaltyBreakScopeResolution = 10;
- verifyFormat("unsigned long foo::\n"
- " bar();",
- Style);
-}
-
-TEST_F(FormatTest, WorksFor8bitEncodings) {
- // FIXME: unstable test case
- EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
- "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
- "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
- "\"\xef\xee\xf0\xf3...\"",
- format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
- "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
- "\xef\xee\xf0\xf3...\"",
- getLLVMStyleWithColumns(12)));
-}
-
-TEST_F(FormatTest, HandlesUTF8BOM) {
- verifyFormat("\xef\xbb\xbf");
- verifyFormat("\xef\xbb\xbf#include <iostream>");
- verifyFormat("\xef\xbb\xbf\n#include <iostream>");
-
- auto Style = getLLVMStyle();
- Style.KeepEmptyLines.AtStartOfFile = false;
- verifyFormat("\xef\xbb\xbf#include <iostream>",
- "\xef\xbb\xbf\n#include <iostream>", Style);
-}
-
-// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
-#if !defined(_MSC_VER)
-
-TEST_F(FormatTest, CountsUTF8CharactersProperly) {
- verifyFormat("\"Однажды в студёную зимнюю пору...\"",
- getLLVMStyleWithColumns(35));
- verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
- getLLVMStyleWithColumns(31));
- verifyFormat("// Однажды в студёную зимнюю пору...",
- getLLVMStyleWithColumns(36));
- verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
- verifyFormat("/* Однажды в студёную зимнюю пору... */",
- getLLVMStyleWithColumns(39));
- verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
- getLLVMStyleWithColumns(35));
-}
-
-TEST_F(FormatTest, SplitsUTF8Strings) {
- // Non-printable characters' width is currently considered to be the length in
- // bytes in UTF8. The characters can be displayed in very different manner
- // (zero-width, single width with a substitution glyph, expanded to their code
- // (e.g. "<8d>"), so there's no single correct way to handle them.
- // FIXME: unstable test case
- EXPECT_EQ("\"aaaaÄ\"\n"
- "\"\xc2\x8d\";",
- format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
- // FIXME: unstable test case
- EXPECT_EQ("\"aaaaaaaÄ\"\n"
- "\"\xc2\x8d\";",
- format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
- // FIXME: unstable test case
- EXPECT_EQ("\"Однажды, в \"\n"
- "\"студёную \"\n"
- "\"зимнюю \"\n"
- "\"пору,\"",
- format("\"Однажды, в студёную зимнюю пору,\"",
- getLLVMStyleWithColumns(13)));
- // FIXME: unstable test case
- EXPECT_EQ(
- "\"一 二 三 \"\n"
- "\"四 五六 \"\n"
- "\"七 八 九 \"\n"
- "\"十\"",
- format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
- // FIXME: unstable test case
- EXPECT_EQ("\"一\t\"\n"
- "\"二 \t\"\n"
- "\"三 四 \"\n"
- "\"五\t\"\n"
- "\"六 \t\"\n"
- "\"七 \"\n"
- "\"八九十\tqq\"",
- format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
- getLLVMStyleWithColumns(11)));
-
- // UTF8 character in an escape sequence.
- // FIXME: unstable test case
- EXPECT_EQ("\"aaaaaa\"\n"
- "\"\\\xC2\x8D\"",
- format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
-}
-
-TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
- verifyFormat("const char *sssss =\n"
- " \"一二三四五六七八\\\n"
- " 九 十\";",
- "const char *sssss = \"一二三四五六七八\\\n"
- " 九 十\";",
- getLLVMStyleWithColumns(30));
-}
-
-TEST_F(FormatTest, SplitsUTF8LineComments) {
- verifyFormat("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10));
- verifyFormat("// Я из лесу\n"
- "// вышел; был\n"
- "// сильный\n"
- "// мороз.",
- "// Я из лесу вышел; был сильный мороз.",
- getLLVMStyleWithColumns(13));
- verifyFormat("// 一二三\n"
- "// 四五六七\n"
- "// 八 九\n"
- "// 十",
- "// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9));
-}
-
-TEST_F(FormatTest, SplitsUTF8BlockComments) {
- verifyFormat("/* Гляжу,\n"
- " * поднимается\n"
- " * медленно в\n"
- " * гору\n"
- " * Лошадка,\n"
- " * везущая\n"
- " * хворосту\n"
- " * воз. */",
- "/* Гляжу, поднимается медленно в гору\n"
- " * Лошадка, везущая хворосту воз. */",
- getLLVMStyleWithColumns(13));
- verifyFormat("/* 一二三\n"
- " * 四五六七\n"
- " * 八 九\n"
- " * 十 */",
- "/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9));
- verifyFormat("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯\n"
- " * 𝕓𝕪𝕥𝕖\n"
- " * 𝖀𝕿𝕱-𝟠 */",
- "/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯 𝕓𝕪𝕥𝕖 𝖀𝕿𝕱-𝟠 */", getLLVMStyleWithColumns(12));
-}
-
-#endif // _MSC_VER
-
-TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
- FormatStyle Style = getLLVMStyle();
-
- Style.ConstructorInitializerIndentWidth = 4;
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
-
- Style.ConstructorInitializerIndentWidth = 2;
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
-
- Style.ConstructorInitializerIndentWidth = 0;
- verifyFormat(
- "SomeClass::Constructor()\n"
- ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
- " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
- Style);
- Style.BreakAfterOpenBracketFunction = true;
- verifyFormat(
- "SomeLongTemplateVariableName<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
- Style);
- verifyFormat("bool smaller = 1 < "
- "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
- " "
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
- Style);
-
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
- verifyFormat("SomeClass::Constructor() :\n"
- "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
- "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
- Style);
-}
-
-TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- Style.ConstructorInitializerIndentWidth = 4;
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- " , b(b)\n"
- " , c(c) {}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a) {}",
- Style);
-
- Style.ColumnLimit = 0;
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a) {}",
- Style);
- verifyFormat("SomeClass::Constructor() noexcept\n"
- " : a(a) {}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- " , b(b)\n"
- " , c(c) {}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a) {\n"
- " foo();\n"
- " bar();\n"
- "}",
- Style);
-
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- " , b(b)\n"
- " , c(c) {\n}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a) {\n}",
- Style);
-
- Style.ColumnLimit = 80;
- Style.AllowShortFunctionsOnASingleLine =
- FormatStyle::ShortFunctionStyle::setAll();
- Style.ConstructorInitializerIndentWidth = 2;
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- " , b(b)\n"
- " , c(c) {}",
- Style);
-
- Style.ConstructorInitializerIndentWidth = 0;
- verifyFormat("SomeClass::Constructor()\n"
- ": a(a)\n"
- ", b(b)\n"
- ", c(c) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- Style.ConstructorInitializerIndentWidth = 4;
- verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
- verifyFormat(
- "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)",
- Style);
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
- Style);
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaaaaa(aaaaaaaa) {}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)",
- Style);
- verifyFormat(
- "SomeClass::Constructor()\n"
- " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
- Style);
-
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
- Style.ConstructorInitializerIndentWidth = 4;
- Style.ColumnLimit = 60;
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaaaaa(aaaaaaaa)\n"
- " , aaaaaaaa(aaaaaaaa)\n"
- " , aaaaaaaa(aaaaaaaa) {}",
- Style);
- Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
- verifyFormat("SomeClass::Constructor()\n"
- " : aaaaaaaa(aaaaaaaa)\n"
- " , aaaaaaaa(aaaaaaaa)\n"
- " , aaaaaaaa(aaaaaaaa) {}",
- Style);
-}
-
-TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
- FormatStyle Style = getLLVMStyle();
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
- Style.ConstructorInitializerIndentWidth = 4;
- verifyFormat("SomeClass::Constructor()\n"
- " : a{a}\n"
- " , b{b} {}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a{a}\n"
- "#if CONDITION\n"
- " , b{b}\n"
- "#endif\n"
- "{\n}",
- Style);
- Style.ConstructorInitializerIndentWidth = 2;
- verifyFormat("SomeClass::Constructor()\n"
- "#if CONDITION\n"
- " : a{a}\n"
- "#endif\n"
- " , b{b}\n"
- " , c{c} {\n}",
- Style);
- Style.ConstructorInitializerIndentWidth = 0;
- verifyFormat("SomeClass::Constructor()\n"
- ": a{a}\n"
- "#ifdef CONDITION\n"
- ", b{b}\n"
- "#else\n"
- ", c{c}\n"
- "#endif\n"
- ", d{d} {\n}",
- Style);
- Style.ConstructorInitializerIndentWidth = 4;
- verifyFormat("SomeClass::Constructor()\n"
- " : a{a}\n"
- "#if WINDOWS\n"
- "#if DEBUG\n"
- " , b{0}\n"
- "#else\n"
- " , b{1}\n"
- "#endif\n"
- "#else\n"
- "#if DEBUG\n"
- " , b{2}\n"
- "#else\n"
- " , b{3}\n"
- "#endif\n"
- "#endif\n"
- "{\n}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a{a}\n"
- "#if WINDOWS\n"
- " , b{0}\n"
- "#if DEBUG\n"
- " , c{0}\n"
- "#else\n"
- " , c{1}\n"
- "#endif\n"
- "#else\n"
- "#if DEBUG\n"
- " , c{2}\n"
- "#else\n"
- " , c{3}\n"
- "#endif\n"
- " , b{1}\n"
- "#endif\n"
- "{\n}",
- Style);
-}
-
-TEST_F(FormatTest, Destructors) {
- verifyFormat("void F(int &i) { i.~int(); }");
- verifyFormat("void F(int &i) { i->~int(); }");
-}
-
-TEST_F(FormatTest, FormatsWithWebKitStyle) {
- FormatStyle Style = getWebKitStyle();
-
- // Don't indent in outer namespaces.
- verifyFormat("namespace outer {\n"
- "int i;\n"
- "namespace inner {\n"
- " int i;\n"
- "} // namespace inner\n"
- "} // namespace outer\n"
- "namespace other_outer {\n"
- "int i;\n"
- "}",
- Style);
-
- // Don't indent case labels.
- verifyFormat("switch (variable) {\n"
- "case 1:\n"
- "case 2:\n"
- " doSomething();\n"
- " break;\n"
- "default:\n"
- " ++variable;\n"
- "}",
- Style);
-
- // Wrap before binary operators.
- verifyFormat(
- "void f()\n"
- "{\n"
- " if (aaaaaaaaaaaaaaaa\n"
- " && bbbbbbbbbbbbbbbbbbbbbbbb\n"
- " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
- " return;\n"
- "}",
- "void f() {\n"
- "if (aaaaaaaaaaaaaaaa\n"
- "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
- "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
- "return;\n"
- "}",
- Style);
-
- // Allow functions on a single line.
- verifyFormat("void f() { return; }", Style);
-
- // Allow empty blocks on a single line and insert a space in empty blocks.
- verifyFormat("void f() { }", "void f() {}", Style);
- verifyFormat("while (true) { }", "while (true) {}", Style);
- // However, don't merge non-empty short loops.
- verifyFormat("while (true) {\n"
- " continue;\n"
- "}",
- "while (true) { continue; }", Style);
-
- // Constructor initializers are formatted one per line with the "," on the
- // new line.
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
- " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
- " aaaaaaaaaaaaaa)\n"
- " , aaaaaaaaaaaaaaaaaaaaaaa()\n"
- "{\n"
- "}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- "{\n"
- "}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- "{\n"
- "}",
- "SomeClass::Constructor():a(a){}", Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- " , b(b)\n"
- " , c(c)\n"
- "{\n"
- "}",
- Style);
- verifyFormat("SomeClass::Constructor()\n"
- " : a(a)\n"
- "{\n"
- " foo();\n"
- " bar();\n"
- "}",
- Style);
-
- // Access specifiers should be aligned left.
- verifyFormat("class C {\n"
- "public:\n"
- " int i;\n"
- "};",
- Style);
-
- // Do not align comments.
- verifyFormat("int a; // Do not\n"
- "double b; // align comments.",
- Style);
-
- // Do not align operands.
- verifyFormat("ASSERT(aaaa\n"
- " || bbbb);",
- "ASSERT ( aaaa\n||bbbb);", Style);
-
- // Accept input's line breaks.
- verifyFormat("if (aaaaaaaaaaaaaaa\n"
- " || bbbbbbbbbbbbbbb) {\n"
- " i++;\n"
- "}",
- "if (aaaaaaaaaaaaaaa\n"
- "|| bbbbbbbbbbbbbbb) { i++; }",
- Style);
- verifyFormat("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
- " i++;\n"
- "}",
- "if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style);
-
- // Don't automatically break all macro definitions (llvm.org/PR17842).
- verifyFormat("#define aNumber 10", Style);
- // However, generally keep the line breaks that the user authored.
- verifyFormat("#define aNumber \\\n"
- " 10",
- "#define aNumber \\\n"
- " 10",
- Style);
-
- // Keep empty and one-element array literals on a single line.
- verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
- " copyItems:YES];",
- "NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
- "copyItems:YES];",
- Style);
- verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
- " copyItems:YES];",
- "NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
- " copyItems:YES];",
- Style);
- // FIXME: This does not seem right, there should be more indentation before
- // the array literal's entries. Nested blocks have the same problem.
- verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
- " @\"a\",\n"
- " @\"a\"\n"
- "]\n"
- " copyItems:YES];",
- "NSArray* a = [[NSArray alloc] initWithArray:@[\n"
- " @\"a\",\n"
- " @\"a\"\n"
- " ]\n"
- " copyItems:YES];",
- Style);
- verifyFormat(
- "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
- " copyItems:YES];",
- "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
- " copyItems:YES];",
- Style);
-
- verifyFormat("[self.a b:c c:d];", Style);
- verifyFormat("[self.a b:c\n"
- " c:d];",
- "[self.a b:c\n"
- "c:d];",
- Style);
-}
-
-TEST_F(FormatTest, FormatsLambdas) {
- verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();");
- verifyFormat(
- "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();");
- verifyFormat("int c = [&] { [=] { return b++; }(); }();");
- verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();");
- verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();");
- verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}");
- verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}");
- verifyFormat("auto c = [a = [b = 42] {}] {};");
- verifyFormat("auto c = [a = &i + 10, b = [] {}] {};");
- verifyFormat("int x = f(*+[] {});");
- verifyFormat("void f() {\n"
- " other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
- "}");
- verifyFormat("void f() {\n"
- " other(x.begin(), //\n"
- " x.end(), //\n"
- " [&](int, int) { return 1; });\n"
- "}");
- verifyFormat("void f() {\n"
- " other.other.other.other.other(\n"
- " x.begin(), x.end(),\n"
- " [something, rather](int, int, int, int, int, int, int) { "
- "return 1; });\n"
- "}");
- verifyFormat(
- "void f() {\n"
- " other.other.other.other.other(\n"
- " x.begin(), x.end(),\n"
- " [something, rather](int, int, int, int, int, int, int) {\n"
- " //\n"
- " });\n"
- "}");
- verifyFormat("SomeFunction([]() { // A cool function...\n"
- " return 43;\n"
- "});");
- verifyFormat("SomeFunction([]() {\n"
- "#define A a\n"
- " return 43;\n"
- "});",
- "SomeFunction([](){\n"
- "#define A a\n"
- "return 43;\n"
- "});");
- verifyFormat("void f() {\n"
- " SomeFunction([](decltype(x), A *a) {});\n"
- " SomeFunction([](typeof(x), A *a) {});\n"
- " SomeFunction([](_Atomic(x), A *a) {});\n"
- " SomeFunction([](__underlying_type(x), A *a) {});\n"
- "}");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " [](const aaaaaaaaaa &a) { return a; });");
- verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
- " SomeOtherFunctioooooooooooooooooooooooooon();\n"
- "});");
- verifyFormat("Constructor()\n"
- " : Field([] { // comment\n"
- " int i;\n"
- " }) {}");
- verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
- " return some_parameter.size();\n"
- "};");
- verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
- " [](const string &s) { return s; };");
- verifyFormat("int i = aaaaaa ? 1 //\n"
- " : [] {\n"
- " return 2; //\n"
- " }();");
- verifyFormat("llvm::errs() << \"number of twos is \"\n"
- " << std::count_if(v.begin(), v.end(), [](int x) {\n"
- " return x == 2; // force break\n"
- " });");
- verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " [=](int iiiiiiiiiiii) {\n"
- " return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
- " aaaaaaaaaaaaaaaaaaaaaaa;\n"
- " });",
- getLLVMStyleWithColumns(60));
-
- verifyFormat("SomeFunction({[&] {\n"
- " // comment\n"
- " },\n"
- " [&] {\n"
- " // comment\n"
- " }});");
- verifyFormat("SomeFunction({[&] {\n"
- " // comment\n"
- "}});");
- verifyFormat(
- "virtual aaaaaaaaaaaaaaaa(\n"
- " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
- " aaaaa aaaaaaaaa);");
-
- // Lambdas with return types.
- verifyFormat("int c = []() -> int { return 2; }();");
- verifyFormat("int c = []() -> int * { return 2; }();");
- verifyFormat("int c = []() -> vector<int> { return {2}; }();");
- verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
- verifyFormat("foo([]() noexcept -> int {});");
- verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
- verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
- verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
- verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
- verifyFormat("[a, a]() -> a<1> {};");
- verifyFormat("[]() -> foo<5 + 2> { return {}; };");
- verifyFormat("[]() -> foo<5 - 2> { return {}; };");
- verifyFormat("[]() -> foo<5 / 2> { return {}; };");
- verifyFormat("[]() -> foo<5 * 2> { return {}; };");
- verifyFormat("[]() -> foo<5 % 2> { return {}; };");
- verifyFormat("[]() -> foo<5 << 2> { return {}; };");
- verifyFormat("[]() -> foo<!5> { return {}; };");
- verifyFormat("[]() -> foo<~5> { return {}; };");
- verifyFormat("[]() -> foo<5 | 2> { return {}; };");
- verifyFormat("[]() -> foo<5 || 2> { return {}; };");
- verifyFormat("[]() -> foo<5 & 2> { return {}; };");
- verifyFormat("[]() -> foo<5 && 2> { return {}; };");
- verifyFormat("[]() -> foo<5 == 2> { return {}; };");
- verifyFormat("[]() -> foo<5 != 2> { return {}; };");
- verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
- verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
- verifyFormat("[]() -> foo<5 < 2> { return {}; };");
- verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<!5> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<~5> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("namespace bar {\n"
- "// broken:\n"
- "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
- "} // namespace bar");
- verifyFormat("[]() -> a<1> {};");
- verifyFormat("[]() -> a<1> { ; };");
- verifyFormat("[]() -> a<1> { ; }();");
- verifyFormat("[a, a]() -> a<true> {};");
- verifyFormat("[]() -> a<true> {};");
- verifyFormat("[]() -> a<true> { ; };");
- verifyFormat("[]() -> a<true> { ; }();");
- verifyFormat("[a, a]() -> a<false> {};");
- verifyFormat("[]() -> a<false> {};");
- verifyFormat("[]() -> a<false> { ; };");
- verifyFormat("[]() -> a<false> { ; }();");
- verifyFormat("auto foo{[]() -> foo<false> { ; }};");
- verifyFormat("namespace bar {\n"
- "auto foo{[]() -> foo<false> { ; }};\n"
- "} // namespace bar");
- verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
- " int j) -> int {\n"
- " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
- "};");
- verifyFormat(
- "aaaaaaaaaaaaaaaaaaaaaa(\n"
- " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
- " return aaaaaaaaaaaaaaaaa;\n"
- " });",
- getLLVMStyleWithColumns(70));
- verifyFormat("[]() //\n"
- " -> int {\n"
- " return 1; //\n"
- "};");
- verifyFormat("[]() -> Void<T...> {};");
- verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
- verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
- verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
- verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
- verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
- verifyFormat("foo([&](u32 bar) __attribute__((always_inline)) -> void {});");
- verifyFormat("return int{[x = x]() { return x; }()};");
-
- // Lambdas with explicit template argument lists.
- verifyFormat(
- "auto L = []<template <typename> class T, class U>(T<U> &&a) {};");
- verifyFormat("auto L = []<class T>(T) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []<class... T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []<typename... T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []<int... T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
- verifyFormat("auto L = []<Foo... T>(T...) {\n"
- " {\n"
- " f();\n"
- " g();\n"
- " }\n"
- "};");
-
- // Lambdas that fit on a single line within an argument list are not forced
- // onto new lines.
- verifyFormat("SomeFunction([] {});");
- verifyFormat("SomeFunction(0, [] {});");
- verifyFormat("SomeFunction([] {}, 0);");
- verifyFormat("SomeFunction(0, [] {}, 0);");
- verifyFormat("SomeFunction([] { return 0; }, 0);");
- verifyFormat("SomeFunction(a, [] { return 0; }, b);");
- verifyFormat("SomeFunction([] { return 0; }, [] { return 0; });");
- verifyFormat("SomeFunction([] { return 0; }, [] { return 0; }, b);");
- verifyFormat("auto loooooooooooooooooooooooooooong =\n"
- " SomeFunction([] { return 0; }, [] { return 0; }, b);");
- // Exceeded column limit. We need to break.
- verifyFormat("auto loooooooooooooooooooooooooooongName = SomeFunction(\n"
- " [] { return anotherLooooooooooonoooooooongName; }, [] { "
- "return 0; }, b);");
-
- // Multiple multi-line lambdas in the same parentheses change indentation
- // rules. These lambdas are always forced to start on new lines.
- verifyFormat("SomeFunction(\n"
- " []() {\n"
- " //\n"
- " },\n"
- " []() {\n"
- " //\n"
- " });");
-
- // A multi-line lambda passed as arg0 is always pushed to the next line.
- verifyFormat("SomeFunction(\n"
- " [this] {\n"
- " //\n"
- " },\n"
- " 1);");
-
- // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
- // the arg0 case above.
- auto Style = getGoogleStyle();
- Style.BinPackArguments = false;
- verifyFormat("SomeFunction(\n"
- " a,\n"
- " [this] {\n"
- " //\n"
- " },\n"
- " b);",
- Style);
- verifyFormat("SomeFunction(\n"
- " a,\n"
- " [this] {\n"
- " //\n"
- " },\n"
- " b);");
-
- // A lambda with a very long line forces arg0 to be pushed out irrespective of
- // the BinPackArguments value (as long as the code is wide enough).
- verifyFormat(
- "something->SomeFunction(\n"
- " a,\n"
- " [this] {\n"
- " "
- "D0000000000000000000000000000000000000000000000000000000000001();\n"
- " },\n"
- " b);");
-
- // A multi-line lambda is pulled up as long as the introducer fits on the
- // previous line and there are no further args.
- verifyFormat("function(1, [this, that] {\n"
- " //\n"
- "});");
- verifyFormat("function([this, that] {\n"
- " //\n"
- "});");
- // FIXME: this format is not ideal and we should consider forcing the first
- // arg onto its own line.
- verifyFormat("function(a, b, c, //\n"
- " d, [this, that] {\n"
- " //\n"
- " });");
-
- // Multiple lambdas are treated correctly even when there is a short arg0.
- verifyFormat("SomeFunction(\n"
- " 1,\n"
- " [this] {\n"
- " //\n"
- " },\n"
- " [this] {\n"
- " //\n"
- " },\n"
- " 1);");
-
- // More complex introducers.
- verifyFormat("return [i, args...] {};");
-
- // Not lambdas.
- verifyFormat("constexpr char hello[]{\"hello\"};");
- verifyFormat("double &operator[](int i) { return 0; }\n"
- "int i;");
- verifyFormat("std::unique_ptr<int[]> foo() {}");
- verifyFormat("int i = a[a][a]->f();");
- verifyFormat("int i = (*b)[a]->f();");
-
- // Other corner cases.
- verifyFormat("void f() {\n"
- " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
- " );\n"
- "}");
- verifyFormat("auto k = *[](int *j) { return j; }(&i);");
-
- // Lambdas created through weird macros.
- verifyFormat("void f() {\n"
- " MACRO((const AA &a) { return 1; });\n"
- " MACRO((AA &a) { return 1; });\n"
- "}");
-
- verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
- " doo_dah();\n"
- " doo_dah();\n"
- " })) {\n"
- "}");
- verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
- " doo_dah();\n"
- " doo_dah();\n"
- " })) {\n"
- "}");
- verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
- " doo_dah();\n"
- " doo_dah();\n"
- " })) {\n"
- "}");
- verifyFormat("auto lambda = []() {\n"
- " int a = 2\n"
- "#if A\n"
- " + 2\n"
- "#endif\n"
- " ;\n"
- "};");
-
- // Lambdas with complex multiline introducers.
- verifyFormat(
- "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
- " -> ::std::unordered_set<\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
- " //\n"
- " });");
-
- FormatStyle LLVMStyle = getLLVMStyleWithColumns(60);
- verifyFormat("very_long_function_name_yes_it_is_really_long(\n"
- " [](auto n) noexcept [[back_attr]]\n"
- " -> std::unordered_map<very_long_type_name_A,\n"
- " very_long_type_name_B> {\n"
- " really_do_something();\n"
- " });",
- LLVMStyle);
- verifyFormat("very_long_function_name_yes_it_is_really_long(\n"
- " [](auto n) constexpr\n"
- " -> std::unordered_map<very_long_type_name_A,\n"
- " very_long_type_name_B> {\n"
- " really_do_something();\n"
- " });",
- LLVMStyle);
-
- FormatStyle DoNotMerge = getLLVMStyle();
- DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
- verifyFormat("auto c = []() {\n"
- " return b;\n"
- "};",
- "auto c = []() { return b; };", DoNotMerge);
- verifyFormat("auto c = []() {\n"
- "};",
- " auto c = []() {};", DoNotMerge);
-
- FormatStyle MergeEmptyOnly = getLLVMStyle();
- MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
- verifyFormat("auto c = []() {\n"
- " return b;\n"
- "};",
- "auto c = []() {\n"
- " return b;\n"
- " };",
- MergeEmptyOnly);
- verifyFormat("auto c = []() {};",
- "auto c = []() {\n"
- "};",
- MergeEmptyOnly);
-
- FormatStyle MergeInline = getLLVMStyle();
- MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
- verifyFormat("auto c = []() {\n"
- " return b;\n"
- "};",
- "auto c = []() { return b; };", MergeInline);
- verifyFormat("function([]() { return b; })", MergeInline);
- verifyFormat("function([]() { return b; }, a)", MergeInline);
- verifyFormat("function(a, []() { return b; })", MergeInline);
- verifyFormat("auto guard = foo{[&] { exit_status = true; }};", MergeInline);
-
- // Check option "BraceWrapping.BeforeLambdaBody" and different state of
- // AllowShortLambdasOnASingleLine
- FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
- LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
- LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_None;
- verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
- " []()\n"
- " {\n"
- " return 17;\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
- " []()\n"
- " {\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto fct_SLS_None = []()\n"
- "{\n"
- " return 17;\n"
- "};",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_None(\n"
- " []()\n"
- " {\n"
- " return Call(\n"
- " []()\n"
- " {\n"
- " return 17;\n"
- " });\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("void Fct() {\n"
- " return {[]()\n"
- " {\n"
- " return 17;\n"
- " }};\n"
- "}",
- LLVMWithBeforeLambdaBody);
-
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_Empty;
- verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
- " []()\n"
- " {\n"
- " return 17;\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
- "ongFunctionName_SLS_Empty(\n"
- " []() {});",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
- " []()\n"
- " {\n"
- " return 17;\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto fct_SLS_Empty = []()\n"
- "{\n"
- " return 17;\n"
- "};",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
- " []()\n"
- " {\n"
- " return Call([]() {});\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
- " []()\n"
- " {\n"
- " return Call([]() {});\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_Empty(\n"
- " []()\n"
- " {\n"
- " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
- " AndShouldNotBeConsiderAsInline,\n"
- " LambdaBodyMustBeBreak);\n"
- " });",
- LLVMWithBeforeLambdaBody);
-
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_Inline;
- verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto fct_SLS_Inline = []()\n"
- "{\n"
- " return 17;\n"
- "};",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
- "17; }); });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_Inline(\n"
- " []()\n"
- " {\n"
- " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
- " AndShouldNotBeConsiderAsInline,\n"
- " LambdaBodyMustBeBreak);\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithMultipleParams_SLS_Inline("
- "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
- " []() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
- LLVMWithBeforeLambdaBody);
-
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_All;
- verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto fct_SLS_All = []() { return 17; };",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneParam_SLS_All(\n"
- " []()\n"
- " {\n"
- " // A cool function...\n"
- " return 43;\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithMultipleParams_SLS_All("
- "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
- " []() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_All(\n"
- " []()\n"
- " {\n"
- " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
- " AndShouldNotBeConsiderAsInline,\n"
- " LambdaBodyMustBeBreak);\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "auto fct_SLS_All = []()\n"
- "{\n"
- " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
- " AndShouldNotBeConsiderAsInline,\n"
- " LambdaBodyMustBeBreak);\n"
- "};",
- LLVMWithBeforeLambdaBody);
- LLVMWithBeforeLambdaBody.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
- " FirstParam,\n"
- " SecondParam,\n"
- " ThirdParam,\n"
- " FourthParam);",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
- " []() { return "
- "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
- " FirstParam,\n"
- " SecondParam,\n"
- " ThirdParam,\n"
- " FourthParam);",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
- " SecondParam,\n"
- " ThirdParam,\n"
- " FourthParam,\n"
- " []() { return SomeValueNotSoLong; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
- " []()\n"
- " {\n"
- " return "
- "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
- "eConsiderAsInline;\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithLongLineInLambda_SLS_All(\n"
- " []()\n"
- " {\n"
- " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
- " AndShouldNotBeConsiderAsInline,\n"
- " LambdaBodyMustBeBreak);\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithTwoParams_SLS_All(\n"
- " []()\n"
- " {\n"
- " // A cool function...\n"
- " return 43;\n"
- " },\n"
- " 87);",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithTwoParams_SLS_All(\n"
- " 87, []() { return LongLineThatWillForceBothParamsToNewLine(); });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "FctWithTwoParams_SLS_All(\n"
- " 87,\n"
- " []()\n"
- " {\n"
- " return "
- "LongLineThatWillForceTheLambdaBodyToBeBrokenIntoMultipleLines();\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
- "}); }, x);",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_All(\n"
- " []()\n"
- " {\n"
- " // A cool function...\n"
- " return Call([]() { return 17; });\n"
- " });",
- LLVMWithBeforeLambdaBody);
- verifyFormat("TwoNestedLambdas_SLS_All(\n"
- " []()\n"
- " {\n"
- " return Call(\n"
- " []()\n"
- " {\n"
- " // A cool function...\n"
- " return 17;\n"
- " });\n"
- " });",
- LLVMWithBeforeLambdaBody);
-
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_None;
-
- verifyFormat("auto select = [this]() -> const Library::Object *\n"
- "{\n"
- " return MyAssignment::SelectFromList(this);\n"
- "};",
- LLVMWithBeforeLambdaBody);
-
- verifyFormat("auto select = [this]() -> const Library::Object &\n"
- "{\n"
- " return MyAssignment::SelectFromList(this);\n"
- "};",
- LLVMWithBeforeLambdaBody);
-
- verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
- "{\n"
- " return MyAssignment::SelectFromList(this);\n"
- "};",
- LLVMWithBeforeLambdaBody);
-
- verifyFormat("namespace test {\n"
- "class Test {\n"
- "public:\n"
- " Test() = default;\n"
- "};\n"
- "} // namespace test",
- LLVMWithBeforeLambdaBody);
-
- // Lambdas with different indentation styles.
- Style = getLLVMStyleWithColumns(60);
- verifyFormat("Result doSomething(Promise promise) {\n"
- " return promise.then(\n"
- " [this, obj = std::move(s)](int bar) mutable {\n"
- " return someObject.startAsyncAction().then(\n"
- " [this, &obj](Result result) mutable {\n"
- " result.processMore();\n"
- " });\n"
- " });\n"
- "}",
- Style);
- Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
- verifyFormat("Result doSomething(Promise promise) {\n"
- " return promise.then(\n"
- " [this, obj = std::move(s)](int bar) mutable {\n"
- " return obj.startAsyncAction().then(\n"
- " [this, &obj](Result result) mutable {\n"
- " result.processMore();\n"
- " });\n"
- " });\n"
- "}",
- Style);
- verifyFormat("Result doSomething(Promise promise) {\n"
- " return promise.then([this, obj = std::move(s)] {\n"
- " return obj.startAsyncAction().then(\n"
- " [this, &obj](Result result) mutable {\n"
- " result.processMore();\n"
- " });\n"
- " });\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " ([]() -> auto {\n"
- " int b = 32;\n"
- " return 3;\n"
- " }).foo();\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " []() -> auto {\n"
- " int b = 32;\n"
- " return 3;\n"
- " }\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " std::sort(v.begin(), v.end(),\n"
- " [](const auto &foo, const auto &bar) {\n"
- " return foo.baz < bar.baz;\n"
- " });\n"
- "};",
- Style);
- verifyFormat("void test() {\n"
- " (\n"
- " []() -> auto {\n"
- " int b = 32;\n"
- " return 3;\n"
- " }, foo, bar)\n"
- " .foo();\n"
- "}",
- Style);
- verifyFormat("void test() {\n"
- " ([]() -> auto {\n"
- " int b = 32;\n"
- " return 3;\n"
- " })\n"
- " .foo()\n"
- " .bar();\n"
- "}",
- Style);
- verifyFormat("#define A \\\n"
- " [] { \\\n"
- " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
- " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
- " }",
- Style);
- verifyFormat("#define SORT(v) \\\n"
- " std::sort(v.begin(), v.end(), \\\n"
- " [](const auto &foo, const auto &bar) { \\\n"
- " return foo.baz < bar.baz; \\\n"
- " });",
- Style);
- verifyFormat("void foo() {\n"
- " aFunction(1, b(c(foo, bar, baz, [](d) {\n"
- " auto f = e(d);\n"
- " return f;\n"
- " })));\n"
- "}",
- Style);
- verifyFormat("void foo() {\n"
- " aFunction(1, b(c(foo, Bar{}, baz, [](d) -> Foo {\n"
- " auto f = e(foo, [&] {\n"
- " auto g = h();\n"
- " return g;\n"
- " }, qux, [&] -> Bar {\n"
- " auto i = j();\n"
- " return i;\n"
- " });\n"
- " return f;\n"
- " })));\n"
- "}",
- Style);
- verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
- " AnotherLongClassName baz)\n"
- " : baz{baz}, func{[&] {\n"
- " auto qux = bar;\n"
- " return aFunkyFunctionCall(qux);\n"
- " }} {}",
- Style);
- verifyFormat("void foo() {\n"
- " class Foo {\n"
- " public:\n"
- " Foo()\n"
- " : qux{[](int quux) {\n"
- " auto tmp = quux;\n"
- " return tmp;\n"
- " }} {}\n"
- "\n"
- " private:\n"
- " std::function<void(int quux)> qux;\n"
- " };\n"
- "}",
- Style);
- Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
- verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
- " AnotherLongClassName baz) :\n"
- " baz{baz}, func{[&] {\n"
- " auto qux = bar;\n"
- " return aFunkyFunctionCall(qux);\n"
- " }} {}",
- Style);
- Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
- verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
- " AnotherLongClassName baz) :\n"
- " baz{baz},\n"
- " func{[&] {\n"
- " auto qux = bar;\n"
- " return aFunkyFunctionCall(qux);\n"
- " }} {}",
- Style);
- Style.BreakAfterOpenBracketFunction = true;
- // FIXME: The following test should pass, but fails at the time of writing.
-#if 0
- // As long as all the non-lambda arguments fit on a single line, AlwaysBreak
- // doesn't force an initial line break, even if lambdas span multiple lines.
- verifyFormat("void foo() {\n"
- " aFunction(\n"
- " [](d) -> Foo {\n"
- " auto f = e(d);\n"
- " return f;\n"
- " }, foo, Bar{}, [] {\n"
- " auto g = h();\n"
- " return g;\n"
- " }, baz);\n"
- "}",
- Style);
-#endif
- // A long non-lambda argument forces arguments to span multiple lines and thus
- // forces an initial line break when using AlwaysBreak.
- verifyFormat("void foo() {\n"
- " aFunction(\n"
- " 1,\n"
- " [](d) -> Foo {\n"
- " auto f = e(d);\n"
- " return f;\n"
- " }, foo, Bar{},\n"
- " [] {\n"
- " auto g = h();\n"
- " return g;\n"
- " }, bazzzzz,\n"
- " quuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux);\n"
- "}",
- Style);
- Style.BinPackArguments = false;
- verifyFormat("void foo() {\n"
- " aFunction(\n"
- " 1,\n"
- " [](d) -> Foo {\n"
- " auto f = e(d);\n"
- " return f;\n"
- " },\n"
- " foo,\n"
- " Bar{},\n"
- " [] {\n"
- " auto g = h();\n"
- " return g;\n"
- " },\n"
- " bazzzzz,\n"
- " quuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux);\n"
- "}",
- Style);
- Style.BinPackArguments = true;
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.BeforeLambdaBody = true;
- verifyFormat("void foo() {\n"
- " aFunction(\n"
- " 1, b(c(foo, Bar{}, baz, [](d) -> Foo\n"
- " {\n"
- " auto f = e(\n"
- " [&]\n"
- " {\n"
- " auto g = h();\n"
- " return g;\n"
- " }, qux, [&] -> Bar\n"
- " {\n"
- " auto i = j();\n"
- " return i;\n"
- " });\n"
- " return f;\n"
- " })));\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, LambdaWithLineComments) {
- FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
- LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
- LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
- LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
- FormatStyle::SLS_All;
-
- verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
- verifyFormat("auto k = []() // comment\n"
- "{ return; }",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto k = []() /* comment */ { return; }",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
- LLVMWithBeforeLambdaBody);
- verifyFormat("auto k = []() // X\n"
- "{ return; }",
- LLVMWithBeforeLambdaBody);
- verifyFormat(
- "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
- "{ return; }",
- LLVMWithBeforeLambdaBody);
-
- LLVMWithBeforeLambdaBody.ColumnLimit = 0;
-
- verifyFormat("foo([]()\n"
- " {\n"
- " bar(); //\n"
- " return 1; // comment\n"
- " }());",
- "foo([]() {\n"
- " bar(); //\n"
- " return 1; // comment\n"
- "}());",
- LLVMWithBeforeLambdaBody);
- verifyFormat("foo(\n"
- " 1, MACRO {\n"
- " baz();\n"
- " bar(); // comment\n"
- " },\n"
- " []() {});",
- "foo(\n"
- " 1, MACRO { baz(); bar(); // comment\n"
- " }, []() {}\n"
- ");",
- LLVMWithBeforeLambdaBody);
-}
-
-TEST_F(FormatTest, EmptyLinesInLambdas) {
- verifyFormat("auto lambda = []() {\n"
- " x(); //\n"
- "};",
- "auto lambda = []() {\n"
- "\n"
- " x(); //\n"
- "\n"
- "};");
-}
-
-TEST_F(FormatTest, LambdaBracesInGNU) {
- auto Style = getGNUStyle();
- EXPECT_EQ(Style.LambdaBodyIndentation, FormatStyle::LBI_Signature);
-
- constexpr StringRef Code("auto x = [&] ()\n"
- " {\n"
- " for (int i = 0; i < y; ++i)\n"
- " return 97;\n"
- " };");
- verifyFormat(Code, Style);
-
- Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
- verifyFormat(Code, Style);
- verifyFormat("for_each_thread ([] (thread_info *thread)\n"
- " {\n"
- " /* Lambda body. */\n"
- " });",
- "for_each_thread([](thread_info *thread) {\n"
- " /* Lambda body. */\n"
- "});",
- Style);
- verifyFormat("iterate_over_lwps (scope_ptid, [=] (struct lwp_info *info)\n"
- " {\n"
- " /* Lambda body. */\n"
- " });",
- "iterate_over_lwps(scope_ptid, [=](struct lwp_info *info) {\n"
- " /* Lambda body. */\n"
- "});",
- Style);
-}
-
-TEST_F(FormatTest, FormatsBlocks) {
- FormatStyle ShortBlocks = getLLVMStyle();
- ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- verifyFormat("int (^Block)(int, int);", ShortBlocks);
- verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
- verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
- verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
- verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
- verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
-
- verifyFormat("foo(^{ bar(); });", ShortBlocks);
- verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
- verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
-
- verifyFormat("[operation setCompletionBlock:^{\n"
- " [self onOperationDone];\n"
- "}];");
- verifyFormat("int i = {[operation setCompletionBlock:^{\n"
- " [self onOperationDone];\n"
- "}]};");
- verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
- " f();\n"
- "}];");
- verifyFormat("int a = [operation block:^int(int *i) {\n"
- " return 1;\n"
- "}];");
- verifyFormat("[myObject doSomethingWith:arg1\n"
- " aaa:^int(int *a) {\n"
- " return 1;\n"
- " }\n"
- " bbb:f(a * bbbbbbbb)];");
-
- verifyFormat("[operation setCompletionBlock:^{\n"
- " [self.delegate newDataAvailable];\n"
- "}];",
- getLLVMStyleWithColumns(60));
- verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
- " NSString *path = [self sessionFilePath];\n"
- " if (path) {\n"
- " // ...\n"
- " }\n"
- "});");
- verifyFormat("[[SessionService sharedService]\n"
- " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
- " if (window) {\n"
- " [self windowDidLoad:window];\n"
- " } else {\n"
- " [self errorLoadingWindow];\n"
- " }\n"
- " }];");
- verifyFormat("void (^largeBlock)(void) = ^{\n"
- " // ...\n"
- "};",
- getLLVMStyleWithColumns(40));
- verifyFormat("[[SessionService sharedService]\n"
- " loadWindowWithCompletionBlock: //\n"
- " ^(SessionWindow *window) {\n"
- " if (window) {\n"
- " [self windowDidLoad:window];\n"
- " } else {\n"
- " [self errorLoadingWindow];\n"
- " }\n"
- " }];",
- getLLVMStyleWithColumns(60));
- verifyFormat("[myObject doSomethingWith:arg1\n"
- " firstBlock:^(Foo *a) {\n"
- " // ...\n"
- " int i;\n"
- " }\n"
- " secondBlock:^(Bar *b) {\n"
- " // ...\n"
- " int i;\n"
- " }\n"
- " thirdBlock:^Foo(Bar *b) {\n"
- " // ...\n"
- " int i;\n"
- " }];");
- verifyFormat("[myObject doSomethingWith:arg1\n"
- " firstBlock:-1\n"
- " secondBlock:^(Bar *b) {\n"
- " // ...\n"
- " int i;\n"
- " }];");
-
- verifyFormat("f(^{\n"
- " @autoreleasepool {\n"
- " if (a) {\n"
- " g();\n"
- " }\n"
- " }\n"
- "});");
- verifyFormat("Block b = ^int *(A *a, B *b) {\n"
- "};");
- verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
- "};");
-
- FormatStyle FourIndent = getLLVMStyle();
- FourIndent.ObjCBlockIndentWidth = 4;
- verifyFormat("[operation setCompletionBlock:^{\n"
- " [self onOperationDone];\n"
- "}];",
- FourIndent);
-}
-
-TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
- FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
-
- verifyFormat("[[SessionService sharedService] "
- "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
- " if (window) {\n"
- " [self windowDidLoad:window];\n"
- " } else {\n"
- " [self errorLoadingWindow];\n"
- " }\n"
- "}];",
- ZeroColumn);
- verifyFormat("[[SessionService sharedService]\n"
- " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
- " if (window) {\n"
- " [self windowDidLoad:window];\n"
- " } else {\n"
- " [self errorLoadingWindow];\n"
- " }\n"
- " }];",
- "[[SessionService sharedService]\n"
- "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
- " if (window) {\n"
- " [self windowDidLoad:window];\n"
- " } else {\n"
- " [self errorLoadingWindow];\n"
- " }\n"
- "}];",
- ZeroColumn);
- verifyFormat("[myObject doSomethingWith:arg1\n"
- " firstBlock:^(Foo *a) {\n"
- " // ...\n"
- " int i;\n"
- " }\n"
- " secondBlock:^(Bar *b) {\n"
- " // ...\n"
- " int i;\n"
- " }\n"
- " thirdBlock:^Foo(Bar *b) {\n"
- " // ...\n"
- " int i;\n"
- " }];",
- ZeroColumn);
- verifyFormat("f(^{\n"
- " @autoreleasepool {\n"
- " if (a) {\n"
- " g();\n"
- " }\n"
- " }\n"
- "});",
- ZeroColumn);
- verifyFormat("void (^largeBlock)(void) = ^{\n"
- " // ...\n"
- "};",
- ZeroColumn);
-
- ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
- verifyFormat("void (^largeBlock)(void) = ^{ int i; };",
- "void (^largeBlock)(void) = ^{ int i; };", ZeroColumn);
- ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
- verifyFormat("void (^largeBlock)(void) = ^{\n"
- " int i;\n"
- "};",
- "void (^largeBlock)(void) = ^{ int i; };", ZeroColumn);
-}
-
-TEST_F(FormatTest, SupportsCRLF) {
- verifyFormat("int a;\r\n"
- "int b;\r\n"
- "int c;",
- "int a;\r\n"
- " int b;\r\n"
- " int c;");
- verifyFormat("int a;\r\n"
- "int b;\r\n"
- "int c;\r\n",
- "int a;\r\n"
- " int b;\n"
- " int c;\r\n");
- verifyFormat("int a;\n"
- "int b;\n"
- "int c;",
- "int a;\r\n"
- " int b;\n"
- " int c;");
- // FIXME: unstable test case
- EXPECT_EQ("\"aaaaaaa \"\r\n"
- "\"bbbbbbb\";\r\n",
- format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
- verifyFormat("#define A \\\r\n"
- " b; \\\r\n"
- " c; \\\r\n"
- " d;",
- "#define A \\\r\n"
- " b; \\\r\n"
- " c; d; ",
- getGoogleStyle());
-
- verifyNoChange("/*\r\n"
- "multi line block comments\r\n"
- "should not introduce\r\n"
- "an extra carriage return\r\n"
- "*/");
- verifyFormat("/*\r\n"
- "\r\n"
- "*/",
- "/*\r\n"
- " \r\r\r\n"
- "*/");
-
- FormatStyle style = getLLVMStyle();
-
- EXPECT_EQ(style.LineEnding, FormatStyle::LE_DeriveLF);
- verifyFormat("union FooBarBazQux {\n"
- " int foo;\n"
- " int bar;\n"
- " int baz;\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- "};",
- style);
- style.LineEnding = FormatStyle::LE_DeriveCRLF;
- verifyFormat("union FooBarBazQux {\r\n"
- " int foo;\r\n"
- " int bar;\r\n"
- " int baz;\r\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- "};",
- style);
-
- style.LineEnding = FormatStyle::LE_LF;
- verifyFormat("union FooBarBazQux {\n"
- " int foo;\n"
- " int bar;\n"
- " int baz;\n"
- " int qux;\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- " int qux;\r\n"
- "};",
- style);
- style.LineEnding = FormatStyle::LE_CRLF;
- verifyFormat("union FooBarBazQux {\r\n"
- " int foo;\r\n"
- " int bar;\r\n"
- " int baz;\r\n"
- " int qux;\r\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- " int qux;\n"
- "};",
- style);
-
- style.LineEnding = FormatStyle::LE_DeriveLF;
- verifyFormat("union FooBarBazQux {\r\n"
- " int foo;\r\n"
- " int bar;\r\n"
- " int baz;\r\n"
- " int qux;\r\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- " int qux;\r\n"
- "};",
- style);
- style.LineEnding = FormatStyle::LE_DeriveCRLF;
- verifyFormat("union FooBarBazQux {\n"
- " int foo;\n"
- " int bar;\n"
- " int baz;\n"
- " int qux;\n"
- "};",
- "union FooBarBazQux {\r\n"
- " int foo;\n"
- " int bar;\r\n"
- " int baz;\n"
- " int qux;\n"
- "};",
- style);
-}
-
-TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
- verifyFormat("MY_CLASS(C) {\n"
- " int i;\n"
- " int j;\n"
- "};");
-}
-
-TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
- FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
- TwoIndent.ContinuationIndentWidth = 2;
-
- verifyFormat("int i =\n"
- " longFunction(\n"
- " arg);",
- "int i = longFunction(arg);", TwoIndent);
-
- FormatStyle SixIndent = getLLVMStyleWithColumns(20);
- SixIndent.ContinuationIndentWidth = 6;
-
- verifyFormat("int i =\n"
- " longFunction(\n"
- " arg);",
- "int i = longFunction(arg);", SixIndent);
-}
-
-TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("int Foo::getter(\n"
- " //\n"
- ") const {\n"
- " return foo;\n"
- "}",
- Style);
- verifyFormat("void Foo::setter(\n"
- " //\n"
- ") {\n"
- " foo = 1;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, SpacesInAngles) {
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
-
- verifyFormat("vector< ::std::string > x1;", Spaces);
- verifyFormat("Foo< int, Bar > x2;", Spaces);
- verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
-
- verifyFormat("static_cast< int >(arg);", Spaces);
- verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
- verifyFormat("f< int, float >();", Spaces);
- verifyFormat("template <> g() {}", Spaces);
- verifyFormat("template < std::vector< int > > f() {}", Spaces);
- verifyFormat("std::function< void(int, int) > fct;", Spaces);
- verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
- Spaces);
-
- Spaces.Standard = FormatStyle::LS_Cpp03;
- Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
- verifyFormat("A< A< int > >();", Spaces);
-
- Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
- verifyFormat("A<A<int> >();", Spaces);
-
- Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
- verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
- Spaces);
- verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
- Spaces);
-
- verifyFormat("A<A<int> >();", Spaces);
- verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
- verifyFormat("A< A< int > >();", Spaces);
-
- Spaces.Standard = FormatStyle::LS_Cpp11;
- Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
- verifyFormat("A< A< int > >();", Spaces);
-
- Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
- verifyFormat("vector<::std::string> x4;", Spaces);
- verifyFormat("vector<int> x5;", Spaces);
- verifyFormat("Foo<int, Bar> x6;", Spaces);
- verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
-
- verifyFormat("A<A<int>>();", Spaces);
-
- Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
- verifyFormat("vector<::std::string> x4;", Spaces);
- verifyFormat("vector< ::std::string > x4;", Spaces);
- verifyFormat("vector<int> x5;", Spaces);
- verifyFormat("vector< int > x5;", Spaces);
- verifyFormat("Foo<int, Bar> x6;", Spaces);
- verifyFormat("Foo< int, Bar > x6;", Spaces);
- verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
- verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
-
- verifyFormat("A<A<int>>();", Spaces);
- verifyFormat("A< A< int > >();", Spaces);
- verifyFormat("A<A<int > >();", Spaces);
- verifyFormat("A< A< int>>();", Spaces);
-
- Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
- verifyFormat("// clang-format off\n"
- "foo<<<1, 1>>>();\n"
- "// clang-format on",
- Spaces);
- verifyFormat("// clang-format off\n"
- "foo< < <1, 1> > >();\n"
- "// clang-format on",
- Spaces);
-}
-
-TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
- FormatStyle Style = getLLVMStyle();
- Style.SpaceAfterTemplateKeyword = false;
- verifyFormat("template<int> void foo();", Style);
-}
-
-TEST_F(FormatTest, TripleAngleBrackets) {
- verifyFormat("f<<<1, 1>>>();");
- verifyFormat("f<<<1, 1, 1, s>>>();");
- verifyFormat("f<<<a, b, c, d>>>();");
- verifyFormat("f<<<1, 1>>>();", "f <<< 1, 1 >>> ();");
- verifyFormat("f<param><<<1, 1>>>();");
- verifyFormat("f<1><<<1, 1>>>();");
- verifyFormat("f<param><<<1, 1>>>();", "f< param > <<< 1, 1 >>> ();");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- "aaaaaaaaaaa<<<\n 1, 1>>>();");
- verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
- " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
-}
-
-TEST_F(FormatTest, MergeLessLessAtEnd) {
- verifyFormat("<<");
- verifyFormat("< < <", "\\\n<<<");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- "aaallvm::outs() <<");
- verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- "aaaallvm::outs()\n <<");
-}
-
-TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
- std::string code = "#if A\n"
- "#if B\n"
- "a.\n"
- "#endif\n"
- " a = 1;\n"
- "#else\n"
- "#endif\n"
- "#if C\n"
- "#else\n"
- "#endif\n";
- verifyFormat(code);
-}
-
-TEST_F(FormatTest, HandleConflictMarkers) {
- // Git/SVN conflict markers.
- verifyFormat("int a;\n"
- "void f() {\n"
- " callme(some(parameter1,\n"
- "<<<<<<< text by the vcs\n"
- " parameter2),\n"
- "||||||| text by the vcs\n"
- " parameter2),\n"
- " parameter3,\n"
- "======= text by the vcs\n"
- " parameter2, parameter3),\n"
- ">>>>>>> text by the vcs\n"
- " otherparameter);",
- "int a;\n"
- "void f() {\n"
- " callme(some(parameter1,\n"
- "<<<<<<< text by the vcs\n"
- " parameter2),\n"
- "||||||| text by the vcs\n"
- " parameter2),\n"
- " parameter3,\n"
- "======= text by the vcs\n"
- " parameter2,\n"
- " parameter3),\n"
- ">>>>>>> text by the vcs\n"
- " otherparameter);");
-
- // Perforce markers.
- verifyFormat("void f() {\n"
- " function(\n"
- ">>>> text by the vcs\n"
- " parameter,\n"
- "==== text by the vcs\n"
- " parameter,\n"
- "==== text by the vcs\n"
- " parameter,\n"
- "<<<< text by the vcs\n"
- " parameter);",
- "void f() {\n"
- " function(\n"
- ">>>> text by the vcs\n"
- " parameter,\n"
- "==== text by the vcs\n"
- " parameter,\n"
- "==== text by the vcs\n"
- " parameter,\n"
- "<<<< text by the vcs\n"
- " parameter);");
-
- verifyNoChange("<<<<<<<\n"
- "|||||||\n"
- "=======\n"
- ">>>>>>>");
-
- verifyNoChange("<<<<<<<\n"
- "|||||||\n"
- "int i;\n"
- "=======\n"
- ">>>>>>>");
-
- // FIXME: Handle parsing of macros around conflict markers correctly:
- verifyFormat("#define Macro \\\n"
- "<<<<<<<\n"
- "Something \\\n"
- "|||||||\n"
- "Else \\\n"
- "=======\n"
- "Other \\\n"
- ">>>>>>>\n"
- " End int i;",
- "#define Macro \\\n"
- "<<<<<<<\n"
- " Something \\\n"
- "|||||||\n"
- " Else \\\n"
- "=======\n"
- " Other \\\n"
- ">>>>>>>\n"
- " End\n"
- "int i;");
-
- verifyFormat(R"(====
-#ifdef A
-a
-#else
-b
-#endif
-)");
-}
-
-TEST_F(FormatTest, DisableRegions) {
- verifyFormat("int i;\n"
- "// clang-format off\n"
- " int j;\n"
- "// clang-format on\n"
- "int k;",
- " int i;\n"
- " // clang-format off\n"
- " int j;\n"
- " // clang-format on\n"
- " int k;");
- verifyFormat("int i;\n"
- "/* clang-format off */\n"
- " int j;\n"
- "/* clang-format on */\n"
- "int k;",
- " int i;\n"
- " /* clang-format off */\n"
- " int j;\n"
- " /* clang-format on */\n"
- " int k;");
-
- // Don't reflow comments within disabled regions.
- verifyFormat("// clang-format off\n"
- "// long long long long long long line\n"
- "/* clang-format on */\n"
- "/* long long long\n"
- " * long long long\n"
- " * line */\n"
- "int i;\n"
- "/* clang-format off */\n"
- "/* long long long long long long line */",
- "// clang-format off\n"
- "// long long long long long long line\n"
- "/* clang-format on */\n"
- "/* long long long long long long line */\n"
- "int i;\n"
- "/* clang-format off */\n"
- "/* long long long long long long line */",
- getLLVMStyleWithColumns(20));
-
- verifyFormat("int *i;\n"
- "// clang-format off:\n"
- "int* j;\n"
- "// clang-format on: 1\n"
- "int *k;",
- "int* i;\n"
- "// clang-format off:\n"
- "int* j;\n"
- "// clang-format on: 1\n"
- "int* k;");
-
- verifyFormat("int *i;\n"
- "// clang-format off:0\n"
- "int* j;\n"
- "// clang-format only\n"
- "int* k;",
- "int* i;\n"
- "// clang-format off:0\n"
- "int* j;\n"
- "// clang-format only\n"
- "int* k;");
-
- verifyNoChange("// clang-format off\n"
- "#if 0\n"
- " #if SHOULD_STAY_INDENTED\n"
- " #endif\n"
- "#endif\n"
- "// clang-format on");
-}
-
-TEST_F(FormatTest, OneLineFormatOffRegex) {
- auto Style = getLLVMStyle();
- Style.OneLineFormatOffRegex = "// format off$";
-
- verifyFormat(" // format off\n"
- " int i ;\n"
- "int j;",
- " // format off\n"
- " int i ;\n"
- " int j ;",
- Style);
- verifyFormat("// format off?\n"
- "int i;",
- " // format off?\n"
- " int i ;",
- Style);
- verifyFormat("f(\"// format off\");", " f(\"// format off\") ;", Style);
-
- verifyFormat("int i;\n"
- " // format off\n"
- " int j ;\n"
- "int k;",
- " int i ;\n"
- " // format off\n"
- " int j ;\n"
- " int k ;",
- Style);
-
- verifyFormat(" // format off\n"
- "\n"
- "int i;",
- " // format off\n"
- " \n"
- " int i ;",
- Style);
-
- verifyFormat("int i;\n"
- " int j ; // format off\n"
- "int k;",
- " int i ;\n"
- " int j ; // format off\n"
- " int k ;",
- Style);
-
- verifyFormat("// clang-format off\n"
- " int i ;\n"
- " int j ; // format off\n"
- " int k ;\n"
- "// clang-format on\n"
- "f();",
- " // clang-format off\n"
- " int i ;\n"
- " int j ; // format off\n"
- " int k ;\n"
- " // clang-format on\n"
- " f() ;",
- Style);
-
- Style.OneLineFormatOffRegex = "^/\\* format off \\*/";
- verifyFormat("int i;\n"
- " /* format off */ int j ;\n"
- "int k;",
- " int i ;\n"
- " /* format off */ int j ;\n"
- " int k ;",
- Style);
- verifyFormat("f(\"/* format off */\");", " f(\"/* format off */\") ;", Style);
-
- Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
- verifyFormat("#define A \\\n"
- " do { \\\n"
- " /* format off */\\\n"
- " f() ; \\\n"
- " g(); \\\n"
- " } while (0)",
- "# define A\\\n"
- " do{ \\\n"
- " /* format off */\\\n"
- " f() ; \\\n"
- " g() ;\\\n"
- " } while (0 )",
- Style);
-
- Style.OneLineFormatOffRegex = "MACRO_TEST";
- verifyNoChange(" MACRO_TEST1 ( ) ;\n"
- " MACRO_TEST2( );",
- Style);
-
- Style.ColumnLimit = 50;
- Style.OneLineFormatOffRegex = "^LogErrorPrint$";
- verifyFormat(" myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
- "myproject::MyLogErrorPrinter(myLogger,\n"
- " \"Split me!\");",
- " myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
- " myproject::MyLogErrorPrinter(myLogger, \"Split me!\");",
- Style);
-
- Style.OneLineFormatOffRegex = "//(< clang-format off| NO_TRANSLATION)$";
- verifyNoChange(
- " int i ; //< clang-format off\n"
- " msg = sprintf(\"Long string with placeholders.\"); // NO_TRANSLATION",
- Style);
-}
-
-TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
- format("? ) =");
- verifyNoCrash("#define a\\\n /**/}");
- verifyNoCrash(" tst %o5 ! are we doing the gray case?\n"
- "LY52: ! [internal]");
-}
-
-TEST_F(FormatTest, FormatsTableGenCode) {
- FormatStyle Style = getLLVMStyle();
- Style.Language = FormatStyle::LK_TableGen;
- verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
-}
-
-TEST_F(FormatTest, ArrayOfTemplates) {
- verifyFormat("auto a = new unique_ptr<int>[10];",
- "auto a = new unique_ptr<int > [ 10];");
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInSquareBrackets = true;
- verifyFormat("auto a = new unique_ptr<int>[ 10 ];",
- "auto a = new unique_ptr<int > [10];", Spaces);
-}
-
-TEST_F(FormatTest, ArrayAsTemplateType) {
- verifyFormat("auto a = unique_ptr<Foo<Bar>[10]>;",
- "auto a = unique_ptr < Foo < Bar>[ 10]> ;");
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInSquareBrackets = true;
- verifyFormat("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
- "auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces);
-}
-
-TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
-
-TEST_F(FormatTest, FormatSortsUsingDeclarations) {
- verifyFormat("using std::cin;\n"
- "using std::cout;",
- "using std::cout;\n"
- "using std::cin;",
- getGoogleStyle());
-}
-
-TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
- FormatStyle Style = getLLVMStyle();
- Style.Standard = FormatStyle::LS_Cpp03;
- // cpp03 recognize this string as identifier u8 and literal character 'a'
- verifyFormat("auto c = u8 'a';", "auto c = u8'a';", Style);
-}
-
-TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
- // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
- // all modes, including C++11, C++14 and C++17
- verifyFormat("auto c = u8'a';");
-}
-
-TEST_F(FormatTest, DoNotFormatLikelyXml) {
- verifyGoogleFormat("<!-- ;> -->");
- verifyNoChange(" <!-- >; -->", getGoogleStyle());
-}
-
-TEST_F(FormatTest, StructuredBindings) {
- // Structured bindings is a C++17 feature.
- // all modes, including C++11, C++14 and C++17
- verifyFormat("auto [a, b] = f();");
- verifyFormat("auto [a, b] = f();", "auto[a, b] = f();");
- verifyFormat("const auto [a, b] = f();", "const auto[a, b] = f();");
- verifyFormat("auto const [a, b] = f();", "auto const[a, b] = f();");
- verifyFormat("auto const volatile [a, b] = f();",
- "auto const volatile[a, b] = f();");
- verifyFormat("auto [a, b, c] = f();", "auto [ a , b,c ] = f();");
- verifyFormat("auto &[a, b, c] = f();", "auto &[ a , b,c ] = f();");
- verifyFormat("auto &&[a, b, c] = f();", "auto &&[ a , b,c ] = f();");
- verifyFormat("auto const &[a, b] = f();", "auto const&[a, b] = f();");
- verifyFormat("auto const volatile &&[a, b] = f();",
- "auto const volatile &&[a, b] = f();");
- verifyFormat("auto const &&[a, b] = f();", "auto const && [a, b] = f();");
- verifyFormat("const auto &[a, b] = f();", "const auto & [a, b] = f();");
- verifyFormat("const auto volatile &&[a, b] = f();",
- "const auto volatile &&[a, b] = f();");
- verifyFormat("volatile const auto &&[a, b] = f();",
- "volatile const auto &&[a, b] = f();");
- verifyFormat("const auto &&[a, b] = f();", "const auto && [a, b] = f();");
-
- // Make sure we don't mistake structured bindings for lambdas.
- FormatStyle PointerMiddle = getLLVMStyle();
- PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
- verifyGoogleFormat("auto [a1, b]{A * i};");
- verifyFormat("auto [a2, b]{A * i};");
- verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
- verifyGoogleFormat("auto const [a1, b]{A * i};");
- verifyFormat("auto const [a2, b]{A * i};");
- verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
- verifyGoogleFormat("auto const& [a1, b]{A * i};");
- verifyFormat("auto const &[a2, b]{A * i};");
- verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
- verifyGoogleFormat("auto const&& [a1, b]{A * i};");
- verifyFormat("auto const &&[a2, b]{A * i};");
- verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
-
- verifyFormat("for (const auto &&[a, b] : some_range) {\n}",
- "for (const auto && [a, b] : some_range) {\n}");
- verifyFormat("for (const auto &[a, b] : some_range) {\n}",
- "for (const auto & [a, b] : some_range) {\n}");
- verifyFormat("for (const auto [a, b] : some_range) {\n}",
- "for (const auto[a, b] : some_range) {\n}");
- verifyFormat("auto [x, y](expr);", "auto[x,y] (expr);");
- verifyFormat("auto &[x, y](expr);", "auto & [x,y] (expr);");
- verifyFormat("auto &&[x, y](expr);", "auto && [x,y] (expr);");
- verifyFormat("auto const &[x, y](expr);", "auto const & [x,y] (expr);");
- verifyFormat("auto const &&[x, y](expr);", "auto const && [x,y] (expr);");
- verifyFormat("auto [x, y]{expr};", "auto[x,y] {expr};");
- verifyFormat("auto const &[x, y]{expr};", "auto const & [x,y] {expr};");
- verifyFormat("auto const &&[x, y]{expr};", "auto const && [x,y] {expr};");
-
- FormatStyle Spaces = getLLVMStyle();
- Spaces.SpacesInSquareBrackets = true;
- verifyFormat("auto [ a, b ] = f();", Spaces);
- verifyFormat("auto &&[ a, b ] = f();", Spaces);
- verifyFormat("auto &[ a, b ] = f();", Spaces);
- verifyFormat("auto const &&[ a, b ] = f();", Spaces);
- verifyFormat("auto const &[ a, b ] = f();", Spaces);
-}
-
-TEST_F(FormatTest, FileAndCode) {
- EXPECT_EQ(FormatStyle::LK_C, guessLanguage("foo.c", ""));
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
- EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
- EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "@interface Foo\n at end"));
- EXPECT_EQ(
- FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
- EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
- EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface Foo\n at end"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int DoStuff(CGRect rect);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage(
- "foo.h", "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));"));
- EXPECT_EQ(
- FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
- // Only one of the two preprocessor regions has ObjC-like code.
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "#if A\n"
- "#define B() C\n"
- "#else\n"
- "#define B() [NSString a:@\"\"]\n"
- "#endif"));
-}
-
-TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "array[[calculator getIndex]];"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
- EXPECT_EQ(
- FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "[[noreturn foo] bar];"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[clang::fallthrough]];"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[using clang: fallthrough]];"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
- EXPECT_EQ(
- FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
- EXPECT_EQ(
- FormatStyle::LK_Cpp,
- guessLanguage("foo.h",
- "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
-}
-
-TEST_F(FormatTest, GuessLanguageWithCaret) {
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
- EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int(^)(char, float);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int(^foo)(char, float);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int(^foo[10])(char, float);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
- EXPECT_EQ(
- FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
-}
-
-TEST_F(FormatTest, GuessLanguageWithPragmas) {
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "__pragma(warning(disable:))"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "#pragma(warning(disable:))"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "_Pragma(warning(disable:))"));
-}
-
-TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
- // ASM symbolic names are identifiers that must be surrounded by [] without
- // space in between:
- // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
-
- // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
- verifyFormat(R"(//
-asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
-)");
-
- // A list of several ASM symbolic names.
- verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
-
- // ASM symbolic names in inline ASM with inputs and outputs.
- verifyFormat(R"(//
-asm("cmoveq %1, %2, %[result]"
- : [result] "=r"(result)
- : "r"(test), "r"(new), "[result]"(old));
-)");
-
- // ASM symbolic names in inline ASM with no outputs.
- verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
-}
-
-TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " asm (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d)\n"
- " [e] \"rm\" (*e));\n"
- "}"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " _asm (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d)\n"
- " [e] \"rm\" (*e));\n"
- "}"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " __asm (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d)\n"
- " [e] \"rm\" (*e));\n"
- "}"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " __asm__ (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d)\n"
- " [e] \"rm\" (*e));\n"
- "}"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " asm (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d),\n"
- " [e] \"rm\" (*e));\n"
- "}"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "void f() {\n"
- " asm volatile (\"mov %[e], %[d]\"\n"
- " : [d] \"=rm\" (d)\n"
- " [e] \"rm\" (*e));\n"
- "}"));
-}
-
-TEST_F(FormatTest, GuessLanguageWithChildLines) {
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
- EXPECT_EQ(
- FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
- EXPECT_EQ(
- FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
-}
-
-TEST_F(FormatTest, GetLanguageByComment) {
- EXPECT_EQ(FormatStyle::LK_C,
- guessLanguage("foo.h", "// clang-format Language: C\n"
- "int i;"));
- EXPECT_EQ(FormatStyle::LK_Cpp,
- guessLanguage("foo.h", "// clang-format Language: Cpp\n"
- "int DoStuff(CGRect rect);"));
- EXPECT_EQ(FormatStyle::LK_ObjC,
- guessLanguage("foo.h", "// clang-format Language: ObjC\n"
- "int i;"));
-}
-
-TEST_F(FormatTest, TypenameMacros) {
- std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
-
- // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
- FormatStyle Google = getGoogleStyleWithColumns(0);
- Google.TypenameMacros = TypenameMacros;
- verifyFormat("struct foo {\n"
- " int bar;\n"
- " TAILQ_ENTRY(a) bleh;\n"
- "};",
- Google);
-
- FormatStyle Macros = getLLVMStyle();
- Macros.TypenameMacros = TypenameMacros;
-
- verifyFormat("STACK_OF(int) a;", Macros);
- verifyFormat("STACK_OF(int) *a;", Macros);
- verifyFormat("STACK_OF(int const *) *a;", Macros);
- verifyFormat("STACK_OF(int *const) *a;", Macros);
- verifyFormat("STACK_OF(int, string) a;", Macros);
- verifyFormat("STACK_OF(LIST(int)) a;", Macros);
- verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
- verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
- verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
- verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
- verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
-
- Macros.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("STACK_OF(int)* a;", Macros);
- verifyFormat("STACK_OF(int*)* a;", Macros);
- verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
- verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
- verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
-}
-
-TEST_F(FormatTest, AtomicQualifier) {
- // Check that we treate _Atomic as a type and not a function call
- FormatStyle Google = getGoogleStyleWithColumns(0);
- verifyFormat("struct foo {\n"
- " int a1;\n"
- " _Atomic(a) a2;\n"
- " _Atomic(_Atomic(int)* const) a3;\n"
- "};",
- Google);
- verifyFormat("_Atomic(uint64_t) a;");
- verifyFormat("_Atomic(uint64_t) *a;");
- verifyFormat("_Atomic(uint64_t const *) *a;");
- verifyFormat("_Atomic(uint64_t *const) *a;");
- verifyFormat("_Atomic(const uint64_t *) *a;");
- verifyFormat("_Atomic(uint64_t) a;");
- verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
- verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
- verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
- verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
-
- verifyFormat("_Atomic(uint64_t) *s(InitValue);");
- verifyFormat("_Atomic(uint64_t) *s{InitValue};");
- FormatStyle Style = getLLVMStyle();
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
- verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
- verifyFormat("_Atomic(int)* a;", Style);
- verifyFormat("_Atomic(int*)* a;", Style);
- verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
-
- Style.SpacesInParens = FormatStyle::SIPO_Custom;
- Style.SpacesInParensOptions.InCStyleCasts = true;
- verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
- Style.SpacesInParensOptions.InCStyleCasts = false;
- Style.SpacesInParensOptions.Other = true;
- verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
- verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
-}
-
-TEST_F(FormatTest, C11Generic) {
- verifyFormat("_Generic(x, int: 1, default: 0)");
- verifyFormat("#define cbrt(X) _Generic((X), float: cbrtf, default: cbrt)(X)");
- verifyFormat("_Generic(x, const char *: 1, char *const: 16, int: 8);");
- verifyFormat("_Generic(x, int: f1, const int: f2)();");
- verifyFormat("_Generic(x, struct A: 1, void (*)(void): 2);");
-
- verifyFormat("_Generic(x,\n"
- " float: f,\n"
- " default: d,\n"
- " long double: ld,\n"
- " float _Complex: fc,\n"
- " double _Complex: dc,\n"
- " long double _Complex: ldc)");
-
- verifyFormat("while (_Generic(x, //\n"
- " long: x)(x) > x) {\n"
- "}");
- verifyFormat("while (_Generic(x, //\n"
- " long: x)(x)) {\n"
- "}");
- verifyFormat("x(_Generic(x, //\n"
- " long: x)(x));");
-
- FormatStyle Style = getLLVMStyle();
- Style.ColumnLimit = 40;
- verifyFormat("#define LIMIT_MAX(T) \\\n"
- " _Generic(((T)0), \\\n"
- " unsigned int: UINT_MAX, \\\n"
- " unsigned long: ULONG_MAX, \\\n"
- " unsigned long long: ULLONG_MAX)",
- Style);
- verifyFormat("_Generic(x,\n"
- " struct A: 1,\n"
- " void (*)(void): 2);",
- Style);
-
- Style.ContinuationIndentWidth = 2;
- verifyFormat("_Generic(x,\n"
- " struct A: 1,\n"
- " void (*)(void): 2);",
- Style);
-}
-
-TEST_F(FormatTest, AmbersandInLamda) {
- // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
- FormatStyle AlignStyle = getLLVMStyle();
- AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
- AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
- verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
-}
-
-TEST_F(FormatTest, TrailingReturnTypeAuto) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("[]() -> auto { return Val; }", Style);
- verifyFormat("[]() -> auto * { return Val; }", Style);
- verifyFormat("[]() -> auto & { return Val; }", Style);
- verifyFormat("auto foo() -> auto { return Val; }", Style);
- verifyFormat("auto foo() -> auto * { return Val; }", Style);
- verifyFormat("auto foo() -> auto & { return Val; }", Style);
-}
-
-TEST_F(FormatTest, SpacesInConditionalStatement) {
- FormatStyle Spaces = getLLVMStyle();
- Spaces.IfMacros.clear();
- Spaces.IfMacros.push_back("MYIF");
- Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
- Spaces.SpacesInParensOptions.InConditionalStatements = true;
- verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces);
- verifyFormat("if ( !a )\n return;", Spaces);
- verifyFormat("if ( a )\n return;", Spaces);
- verifyFormat("if constexpr ( a )\n return;", Spaces);
- verifyFormat("MYIF ( a )\n return;", Spaces);
- verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces);
- verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces);
- verifyFormat("switch ( a )\ncase 1:\n return;", Spaces);
- verifyFormat("while ( a )\n return;", Spaces);
- verifyFormat("while ( (a && b) )\n return;", Spaces);
- verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
- verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
- // Check that space on the left of "::" is inserted as expected at beginning
- // of condition.
- verifyFormat("while ( ::func() )\n return;", Spaces);
-
- // Check impact of ControlStatementsExceptControlMacros is honored.
- Spaces.SpaceBeforeParens =
- FormatStyle::SBPO_ControlStatementsExceptControlMacros;
- verifyFormat("MYIF( a )\n return;", Spaces);
- verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces);
- verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces);
-}
-
-TEST_F(FormatTest, SpaceInEmptyBraces) {
- constexpr StringRef Code("void f() {}\n"
- "class Unit {};\n"
- "auto a = [] {};\n"
- "int x{};");
- verifyFormat(Code);
-
- auto Style = getWebKitStyle();
- EXPECT_EQ(Style.SpaceInEmptyBraces, FormatStyle::SIEB_Always);
-
- verifyFormat("void f() { }\n"
- "class Unit { };\n"
- "auto a = [] { };\n"
- "int x { };",
- Code, Style);
-
- Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
- verifyFormat("void f() { }\n"
- "class Unit { };\n"
- "auto a = [] { };\n"
- "int x {};",
- Code, Style);
-}
-
-TEST_F(FormatTest, AlternativeOperators) {
- // Test case for ensuring alternate operators are not
- // combined with their right most neighbour.
- verifyFormat("int a and b;");
- verifyFormat("int a and_eq b;");
- verifyFormat("int a bitand b;");
- verifyFormat("int a bitor b;");
- verifyFormat("int a compl b;");
- verifyFormat("int a not b;");
- verifyFormat("int a not_eq b;");
- verifyFormat("int a or b;");
- verifyFormat("int a xor b;");
- verifyFormat("int a xor_eq b;");
- verifyFormat("return this not_eq bitand other;");
- verifyFormat("bool operator not_eq(const X bitand other)");
-
- verifyFormat("int a and 5;");
- verifyFormat("int a and_eq 5;");
- verifyFormat("int a bitand 5;");
- verifyFormat("int a bitor 5;");
- verifyFormat("int a compl 5;");
- verifyFormat("int a not 5;");
- verifyFormat("int a not_eq 5;");
- verifyFormat("int a or 5;");
- verifyFormat("int a xor 5;");
- verifyFormat("int a xor_eq 5;");
-
- verifyFormat("int a compl(5);");
- verifyFormat("int a not(5);");
-
- verifyFormat("compl foo();"); // ~foo();
- verifyFormat("foo() <%%>"); // foo() {}
- verifyFormat("void foo() <%%>"); // void foo() {}
- verifyFormat("int a<:1:>;"); // int a[1];
- verifyFormat("%:define ABC abc"); // #define ABC abc
- verifyFormat("%:%:"); // ##
-
- verifyFormat("return not ::f();");
- verifyFormat("return not *foo;");
-
- verifyFormat("a = v(not;);\n"
- "c = v(not x);\n"
- "d = v(not 1);\n"
- "e = v(not 123.f);");
-
- verifyNoChange("#define ASSEMBLER_INSTRUCTION_LIST(V) \\\n"
- " V(and) \\\n"
- " V(not) \\\n"
- " V(other)",
- getLLVMStyleWithColumns(40));
-}
-
-TEST_F(FormatTest, STLWhileNotDefineChed) {
- verifyFormat("#if defined(while)\n"
- "#define while EMIT WARNING C4005\n"
- "#endif // while");
-}
-
-TEST_F(FormatTest, OperatorSpacing) {
- FormatStyle Style = getLLVMStyle();
- Style.PointerAlignment = FormatStyle::PAS_Right;
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("Foo::operator void *();", Style);
- verifyFormat("Foo::operator void **();", Style);
- verifyFormat("Foo::operator void *&();", Style);
- verifyFormat("Foo::operator void *&&();", Style);
- verifyFormat("Foo::operator void const *();", Style);
- verifyFormat("Foo::operator void const **();", Style);
- verifyFormat("Foo::operator void const *&();", Style);
- verifyFormat("Foo::operator void const *&&();", Style);
- verifyFormat("Foo::operator()(void *);", Style);
- verifyFormat("Foo::operator*(void *);", Style);
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("Foo::operator**();", Style);
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("Foo::operator<int> *();", Style);
- verifyFormat("Foo::operator<Foo> *();", Style);
- verifyFormat("Foo::operator<int> **();", Style);
- verifyFormat("Foo::operator<Foo> **();", Style);
- verifyFormat("Foo::operator<int> &();", Style);
- verifyFormat("Foo::operator<Foo> &();", Style);
- verifyFormat("Foo::operator<int> &&();", Style);
- verifyFormat("Foo::operator<Foo> &&();", Style);
- verifyFormat("Foo::operator<int> *&();", Style);
- verifyFormat("Foo::operator<Foo> *&();", Style);
- verifyFormat("Foo::operator<int> *&&();", Style);
- verifyFormat("Foo::operator<Foo> *&&();", Style);
- verifyFormat("operator*(int (*)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("Foo::operator void &();", Style);
- verifyFormat("Foo::operator void const &();", Style);
- verifyFormat("Foo::operator()(void &);", Style);
- verifyFormat("Foo::operator&(void &);", Style);
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("operator&(int (&)(), class Foo);", Style);
- verifyFormat("operator&&(int (&)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("Foo::operator**();", Style);
- verifyFormat("Foo::operator void &&();", Style);
- verifyFormat("Foo::operator void const &&();", Style);
- verifyFormat("Foo::operator()(void &&);", Style);
- verifyFormat("Foo::operator&&(void &&);", Style);
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("operator&&(int (&&)(), class Foo);", Style);
- verifyFormat("operator const nsTArrayRight<E> &()", Style);
- verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
- Style);
- verifyFormat("operator void **()", Style);
- verifyFormat("operator const FooRight<Object> &()", Style);
- verifyFormat("operator const FooRight<Object> *()", Style);
- verifyFormat("operator const FooRight<Object> **()", Style);
- verifyFormat("operator const FooRight<Object> *&()", Style);
- verifyFormat("operator const FooRight<Object> *&&()", Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Left;
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("Foo::operator**();", Style);
- verifyFormat("Foo::operator void*();", Style);
- verifyFormat("Foo::operator void**();", Style);
- verifyFormat("Foo::operator void*&();", Style);
- verifyFormat("Foo::operator void*&&();", Style);
- verifyFormat("Foo::operator void const*();", Style);
- verifyFormat("Foo::operator void const**();", Style);
- verifyFormat("Foo::operator void const*&();", Style);
- verifyFormat("Foo::operator void const*&&();", Style);
- verifyFormat("Foo::operator/*comment*/ void*();", Style);
- verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
- verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
- verifyFormat("Foo::operator()(void*);", Style);
- verifyFormat("Foo::operator*(void*);", Style);
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("Foo::operator<int>*();", Style);
- verifyFormat("Foo::operator<Foo>*();", Style);
- verifyFormat("Foo::operator<int>**();", Style);
- verifyFormat("Foo::operator<Foo>**();", Style);
- verifyFormat("Foo::operator<Foo>*&();", Style);
- verifyFormat("Foo::operator<int>&();", Style);
- verifyFormat("Foo::operator<Foo>&();", Style);
- verifyFormat("Foo::operator<int>&&();", Style);
- verifyFormat("Foo::operator<Foo>&&();", Style);
- verifyFormat("Foo::operator<int>*&();", Style);
- verifyFormat("Foo::operator<Foo>*&();", Style);
- verifyFormat("operator*(int (*)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("Foo::operator void&();", Style);
- verifyFormat("Foo::operator void const&();", Style);
- verifyFormat("Foo::operator/*comment*/ void&();", Style);
- verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
- verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
- verifyFormat("Foo::operator()(void&);", Style);
- verifyFormat("Foo::operator&(void&);", Style);
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("operator&(int (&)(), class Foo);", Style);
- verifyFormat("operator&(int (&&)(), class Foo);", Style);
- verifyFormat("operator&&(int (&&)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("Foo::operator void&&();", Style);
- verifyFormat("Foo::operator void const&&();", Style);
- verifyFormat("Foo::operator/*comment*/ void&&();", Style);
- verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
- verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
- verifyFormat("Foo::operator()(void&&);", Style);
- verifyFormat("Foo::operator&&(void&&);", Style);
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("operator&&(int (&&)(), class Foo);", Style);
- verifyFormat("operator const nsTArrayLeft<E>&()", Style);
- verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
- Style);
- verifyFormat("operator void**()", Style);
- verifyFormat("operator const FooLeft<Object>&()", Style);
- verifyFormat("operator const FooLeft<Object>*()", Style);
- verifyFormat("operator const FooLeft<Object>**()", Style);
- verifyFormat("operator const FooLeft<Object>*&()", Style);
- verifyFormat("operator const FooLeft<Object>*&&()", Style);
-
- // PR45107
- verifyFormat("operator Vector<String>&();", Style);
- verifyFormat("operator const Vector<String>&();", Style);
- verifyFormat("operator foo::Bar*();", Style);
- verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
- verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
- Style);
-
- Style.PointerAlignment = FormatStyle::PAS_Middle;
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("Foo::operator void *();", Style);
- verifyFormat("Foo::operator()(void *);", Style);
- verifyFormat("Foo::operator*(void *);", Style);
- verifyFormat("Foo::operator*();", Style);
- verifyFormat("operator*(int (*)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("Foo::operator void &();", Style);
- verifyFormat("Foo::operator void const &();", Style);
- verifyFormat("Foo::operator()(void &);", Style);
- verifyFormat("Foo::operator&(void &);", Style);
- verifyFormat("Foo::operator&();", Style);
- verifyFormat("operator&(int (&)(), class Foo);", Style);
-
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("Foo::operator void &&();", Style);
- verifyFormat("Foo::operator void const &&();", Style);
- verifyFormat("Foo::operator()(void &&);", Style);
- verifyFormat("Foo::operator&&(void &&);", Style);
- verifyFormat("Foo::operator&&();", Style);
- verifyFormat("operator&&(int (&&)(), class Foo);", Style);
-}
-
-TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
- FormatStyle Style = getLLVMStyle();
- // PR46157
- verifyFormat("foo(operator+, -42);", Style);
- verifyFormat("foo(operator++, -42);", Style);
- verifyFormat("foo(operator--, -42);", Style);
- verifyFormat("foo(-42, operator--);", Style);
- verifyFormat("foo(-42, operator, );", Style);
- verifyFormat("foo(operator, , -42);", Style);
-}
-
-TEST_F(FormatTest, LineSpliceWithTrailingWhitespace) {
- auto Style = getLLVMStyle();
- Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
- Style.UseTab = FormatStyle::UT_Never;
-
- verifyFormat("int i;", " \\ \n"
- " int i;");
- verifyFormat("#define FOO(args) \\\n"
- " struct a {};",
- "#define FOO( args ) \\ \n"
- "struct a{\\\t\t\t\n"
- " };",
- Style);
-}
-
-TEST_F(FormatTest, WhitespaceSensitiveMacros) {
- FormatStyle Style = getLLVMStyle();
- Style.WhitespaceSensitiveMacros.push_back("FOO");
-
- // Newlines are important here.
- verifyNoChange("FOO(1+2 )\n", Style);
- verifyNoChange("FOO(a:b:c)\n", Style);
-
- // Don't use the helpers here, since 'mess up' will change the whitespace
- // and these are all whitespace sensitive by definition
- verifyNoChange("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style);
- verifyNoChange("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style);
- verifyNoChange("FOO(String-ized&Messy+But,: :Still=Intentional);", Style);
- verifyNoChange("FOO(String-ized&Messy+But,: :\n"
- " Still=Intentional);",
- Style);
- Style.AlignConsecutiveAssignments.Enabled = true;
- verifyNoChange("FOO(String-ized=&Messy+But,: :\n"
- " Still=Intentional);",
- Style);
-
- Style.ColumnLimit = 21;
- verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
-}
-
-TEST_F(FormatTest, SkipMacroDefinitionBody) {
- auto Style = getLLVMStyle();
- Style.SkipMacroDefinitionBody = true;
-
- verifyFormat("#define A", "#define A", Style);
- verifyFormat("#define A a aa", "#define A a aa", Style);
- verifyNoChange("#define A b", Style);
- verifyNoChange("#define A ( args )", Style);
- verifyNoChange("#define A ( args ) = func ( args )", Style);
- verifyNoChange("#define A ( args ) { int a = 1 ; }", Style);
- verifyNoChange("#define A ( args ) \\\n"
- " {\\\n"
- " int a = 1 ;\\\n"
- "}",
- Style);
-
- verifyNoChange("#define A x:", Style);
- verifyNoChange("#define A a. b", Style);
-
- // Surrounded with formatted code.
- verifyFormat("int a;\n"
- "#define A a\n"
- "int a;",
- "int a ;\n"
- "#define A a\n"
- "int a ;",
- Style);
-
- // Columns are not broken when a limit is set.
- Style.ColumnLimit = 10;
- verifyFormat("#define A a a a a", " # define A a a a a ", Style);
- verifyNoChange("#define A a a a a", Style);
-
- Style.ColumnLimit = 15;
- verifyFormat("#define A // a\n"
- " // very\n"
- " // long\n"
- " // comment",
- "#define A //a very long comment", Style);
- Style.ColumnLimit = 0;
-
- // Multiline definition.
- verifyNoChange("#define A \\\n"
- "Line one with spaces . \\\n"
- " Line two.",
- Style);
- verifyNoChange("#define A \\\n"
- "a a \\\n"
- "a \\\n"
- "a",
- Style);
- Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
- verifyNoChange("#define A \\\n"
- "a a \\\n"
- "a \\\n"
- "a",
- Style);
- Style.AlignEscapedNewlines = FormatStyle::ENAS_Right;
- verifyNoChange("#define A \\\n"
- "a a \\\n"
- "a \\\n"
- "a",
- Style);
-
- Style.IndentPPDirectives = FormatStyle::PPDIS_Leave;
- verifyNoChange("#if A\n"
- "#define A a\n"
- "#endif",
- Style);
- verifyNoChange("#if A\n"
- " #define A a\n"
- "#endif",
- Style);
- verifyNoChange("#if A\n"
- "# define A a\n"
- "#endif",
- Style);
-
- // Adjust indendations but don't change the definition.
- Style.IndentPPDirectives = FormatStyle::PPDIS_None;
- verifyNoChange("#if A\n"
- "#define A a\n"
- "#endif",
- Style);
- verifyFormat("#if A\n"
- "#define A a\n"
- "#endif",
- "#if A\n"
- " #define A a\n"
- "#endif",
- Style);
- Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
- verifyNoChange("#if A\n"
- "# define A a\n"
- "#endif",
- Style);
- verifyFormat("#if A\n"
- "# define A a\n"
- "#endif",
- "#if A\n"
- " #define A a\n"
- "#endif",
- Style);
- Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
- verifyNoChange("#if A\n"
- " #define A a\n"
- "#endif",
- Style);
- verifyFormat("#if A\n"
- " #define A a\n"
- "#endif",
- "#if A\n"
- " # define A a\n"
- "#endif",
- Style);
-
- Style.IndentPPDirectives = FormatStyle::PPDIS_None;
- // SkipMacroDefinitionBody should not affect other PP directives
- verifyFormat("#if !defined(A)\n"
- "#define A a\n"
- "#endif",
- "#if ! defined ( A )\n"
- " #define A a\n"
- "#endif",
- Style);
-
- // With comments.
- verifyFormat("/* */ #define A a // a a", "/* */ # define A a // a a",
- Style);
- verifyNoChange("/* */ #define A a // a a", Style);
-
- verifyFormat("int a; // a\n"
- "#define A // a\n"
- "int aaa; // a",
- "int a; // a\n"
- "#define A // a\n"
- "int aaa; // a",
- Style);
-
- verifyNoChange(
- "#define MACRO_WITH_COMMENTS() \\\n"
- " public: \\\n"
- " /* Documentation parsed by Doxygen for the following method. */ \\\n"
- " static MyType getClassTypeId(); \\\n"
- " /** Normal comment for the following method. */ \\\n"
- " virtual MyType getTypeId() const;",
- Style);
-
- // multiline macro definitions
- verifyNoChange("#define A a\\\n"
- " A a \\\n "
- " A a",
- Style);
- verifyNoChange("#define MY_MACRO \\\n"
- " /*foo*//*bar*/ \\\n"
- " /* comment */ \\\n"
- " 1",
- Style);
-}
-
-TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
- // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
- // test its interaction with line wrapping
- FormatStyle Style = getLLVMStyleWithColumns(80);
- verifyFormat("namespace {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace",
- Style);
-
- verifyFormat("namespace AAA {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace AAA",
- Style);
-
- verifyFormat("namespace Averyveryveryverylongnamespace {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace Averyveryveryverylongnamespace",
- "namespace Averyveryveryverylongnamespace {\n"
- "int i;\n"
- "int j;\n"
- "}",
- Style);
-
- verifyFormat(
- "namespace "
- "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
- " went::mad::now {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace\n"
- " // "
- "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
- "went::mad::now",
- "namespace "
- "would::it::save::you::a::lot::of::time::if_::i::"
- "just::gave::up::and_::went::mad::now {\n"
- "int i;\n"
- "int j;\n"
- "}",
- Style);
-
- // This used to duplicate the comment again and again on subsequent runs
- verifyFormat(
- "namespace "
- "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
- " went::mad::now {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace\n"
- " // "
- "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
- "went::mad::now",
- "namespace "
- "would::it::save::you::a::lot::of::time::if_::i::"
- "just::gave::up::and_::went::mad::now {\n"
- "int i;\n"
- "int j;\n"
- "} // namespace\n"
- " // "
- "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
- "and_::went::mad::now",
- Style);
-}
-
-TEST_F(FormatTest, LikelyUnlikely) {
- FormatStyle Style = getLLVMStyle();
-
- verifyFormat("if (argc > 5) [[unlikely]] {\n"
- " return 29;\n"
- "}",
- Style);
-
- verifyFormat("if (argc > 5) [[likely]] {\n"
- " return 29;\n"
- "}",
- Style);
-
- verifyFormat("if (argc > 5) [[unlikely]] {\n"
- " return 29;\n"
- "} else [[likely]] {\n"
- " return 42;\n"
- "}",
- Style);
-
- verifyFormat("if (argc > 5) [[unlikely]] {\n"
- " return 29;\n"
- "} else if (argc > 10) [[likely]] {\n"
- " return 99;\n"
- "} else {\n"
- " return 42;\n"
- "}",
- Style);
-
- verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
- " return 29;\n"
- "}",
- Style);
-
- verifyFormat("if (argc > 5) [[unlikely]]\n"
- " return 29;",
- Style);
- verifyFormat("if (argc > 5) [[likely]]\n"
- " return 29;",
- Style);
-
- verifyFormat("while (limit > 0) [[unlikely]] {\n"
- " --limit;\n"
- "}",
- Style);
- verifyFormat("for (auto &limit : limits) [[likely]] {\n"
- " --limit;\n"
- "}",
- Style);
-
- verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
- " --limit;",
- Style);
- verifyFormat("while (limit > 0) [[likely]]\n"
- " --limit;",
- Style);
-
- Style.AttributeMacros.push_back("UNLIKELY");
- Style.AttributeMacros.push_back("LIKELY");
- verifyFormat("if (argc > 5) UNLIKELY\n"
- " return 29;",
- Style);
-
- verifyFormat("if (argc > 5) UNLIKELY {\n"
- " return 29;\n"
- "}",
- Style);
- verifyFormat("if (argc > 5) UNLIKELY {\n"
- " return 29;\n"
- "} else [[likely]] {\n"
- " return 42;\n"
- "}",
- Style);
- verifyFormat("if (argc > 5) UNLIKELY {\n"
- " return 29;\n"
- "} else LIKELY {\n"
- " return 42;\n"
- "}",
- Style);
- verifyFormat("if (argc > 5) [[unlikely]] {\n"
- " return 29;\n"
- "} else LIKELY {\n"
- " return 42;\n"
- "}",
- Style);
-
- verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
- " --limit;\n"
- "}",
- Style);
- verifyFormat("while (limit > 0) LIKELY {\n"
- " --limit;\n"
- "}",
- Style);
-
- verifyFormat("while (limit > 0) UNLIKELY\n"
- " --limit;",
- Style);
- verifyFormat("for (auto &limit : limits) LIKELY\n"
- " --limit;",
- Style);
-}
-
-TEST_F(FormatTest, PenaltyIndentedWhitespace) {
- verifyFormat("Constructor()\n"
- " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaa(aaaaaaaaaaaaaaaaaa, "
- "aaaaaaaaaaaaaaaaaat))");
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaa), "
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
-
- FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
- StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
- verifyFormat("Constructor()\n"
- " : aaaaaa(aaaaaa),\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
- StyleWithWhitespacePenalty);
- verifyFormat("Constructor()\n"
- " : aaaaaaaaaaaaa(aaaaaa), "
- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
- StyleWithWhitespacePenalty);
-}
-
-TEST_F(FormatTest, LLVMDefaultStyle) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("extern \"C\" {\n"
- "int foo();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, GNUDefaultStyle) {
- FormatStyle Style = getGNUStyle();
- verifyFormat("extern \"C\"\n"
- "{\n"
- " int foo ();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, MozillaDefaultStyle) {
- FormatStyle Style = getMozillaStyle();
- verifyFormat("extern \"C\"\n"
- "{\n"
- " int foo();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, GoogleDefaultStyle) {
- FormatStyle Style = getGoogleStyle();
- verifyFormat("extern \"C\" {\n"
- "int foo();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, ChromiumDefaultStyle) {
- FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
- verifyFormat("extern \"C\" {\n"
- "int foo();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, MicrosoftDefaultStyle) {
- FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_Cpp);
- verifyFormat("extern \"C\"\n"
- "{\n"
- " int foo();\n"
- "}",
- Style);
-}
-TEST_F(FormatTest, WebKitDefaultStyle) {
- FormatStyle Style = getWebKitStyle();
- verifyFormat("extern \"C\" {\n"
- "int foo();\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, Concepts) {
- EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
- FormatStyle::BBCDS_Always);
-
- // The default in LLVM style is REI_OuterScope, but these tests were written
- // when the default was REI_Keyword.
- FormatStyle Style = getLLVMStyle();
- Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
-
- verifyFormat("template <typename T>\n"
- "concept True = true;");
-
- verifyFormat("template <typename T>\n"
- "concept C = ((false || foo()) && C2<T>) ||\n"
- " (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
- getLLVMStyleWithColumns(60));
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
- "sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = true && requires(T t) {\n"
- " t.bar();\n"
- " t.baz();\n"
- " } && sizeof(T) <= 8;",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = true && requires(T t) { // Comment\n"
- " t.bar();\n"
- " t.baz();\n"
- " } && sizeof(T) <= 8;",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
- "sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = Unit<T> && !DerivedUnit<T>;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = Unit<T> && !(DerivedUnit<T>);");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = Unit<T> && !!DerivedUnit<T>;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
- "&& sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck =\n"
- " static_cast<bool>(0) || requires(T t) { t.bar(); } && "
- "sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
- "&& sizeof(T) <= 8;");
-
- verifyFormat(
- "template <typename T>\n"
- "concept DelayedCheck =\n"
- " (bool)(0) || requires(T t) { t.bar(); } && sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
- "&& sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
- "sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
- " requires(T t) {\n"
- " t.bar();\n"
- " t.baz();\n"
- " } && sizeof(T) <= 8 && !(4 < 3);",
- getLLVMStyleWithColumns(60));
-
- verifyFormat("template <typename T>\n"
- "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
-
- verifyFormat("template <typename T>\n"
- "concept C = foo();");
-
- verifyFormat("template <typename T>\n"
- "concept C = foo(T());");
-
- verifyFormat("template <typename T>\n"
- "concept C = foo(T{});");
-
- verifyFormat("template <typename T>\n"
- "concept Size = V<sizeof(T)>::Value > 5;");
-
- verifyFormat("template <typename T>\n"
- "concept True = S<T>::Value;");
-
- verifyFormat("template <S T>\n"
- "concept True = T.field;");
-
- verifyFormat(
- "template <typename T>\n"
- "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
- " sizeof(T) <= 8;");
-
- // FIXME: This is misformatted because the fake l paren starts at bool, not at
- // the lambda l square.
- verifyFormat("template <typename T>\n"
- "concept C = [] -> bool { return true; }() && requires(T t) { "
- "t.bar(); } &&\n"
- " sizeof(T) <= 8;");
-
- verifyFormat(
- "template <typename T>\n"
- "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
- " requires(T t) { t.bar(); } && sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept C = decltype([]() { return std::true_type{}; "
- "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
- getLLVMStyleWithColumns(120));
-
- verifyFormat("template <typename T>\n"
- "concept C = decltype([]() -> std::true_type { return {}; "
- "}())::value &&\n"
- " requires(T t) { t.bar(); } && sizeof(T) <= 8;");
-
- verifyFormat("template <typename T>\n"
- "concept C = true;\n"
- "Foo Bar;");
-
- verifyFormat("template <typename T>\n"
- "concept Hashable = requires(T a) {\n"
- " { std::hash<T>{}(a) } -> "
- "std::convertible_to<std::size_t>;\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "concept EqualityComparable = requires(T a, T b) {\n"
- " { a == b } -> std::same_as<bool>;\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "concept EqualityComparable = requires(T a, T b) {\n"
- " { a == b } -> std::same_as<bool>;\n"
- " { a != b } -> std::same_as<bool>;\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept WeakEqualityComparable = requires(T a, T b) {\n"
- " { a == b };\n"
- " { a != b };\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept HasSizeT = requires { typename T::size_t; };");
-
- verifyFormat("template <typename T>\n"
- "concept Semiregular =\n"
- " DefaultConstructible<T> && CopyConstructible<T> && "
- "CopyAssignable<T> &&\n"
- " requires(T a, std::size_t n) {\n"
- " requires Same<T *, decltype(&a)>;\n"
- " { a.~T() } noexcept;\n"
- " requires Same<T *, decltype(new T)>;\n"
- " requires Same<T *, decltype(new T[n])>;\n"
- " { delete new T; };\n"
- " { delete new T[n]; };\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept Semiregular =\n"
- " requires(T a, std::size_t n) {\n"
- " requires Same<T *, decltype(&a)>;\n"
- " { a.~T() } noexcept;\n"
- " requires Same<T *, decltype(new T)>;\n"
- " requires Same<T *, decltype(new T[n])>;\n"
- " { delete new T; };\n"
- " { delete new T[n]; };\n"
- " { new T } -> std::same_as<T *>;\n"
- " } && DefaultConstructible<T> && CopyConstructible<T> && "
- "CopyAssignable<T>;",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "concept Semiregular =\n"
- " DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
- " requires Same<T *, decltype(&a)>;\n"
- " { a.~T() } noexcept;\n"
- " requires Same<T *, decltype(new T)>;\n"
- " requires Same<T *, decltype(new "
- "T[n])>;\n"
- " { delete new T; };\n"
- " { delete new T[n]; };\n"
- " } && CopyConstructible<T> && "
- "CopyAssignable<T>;",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept Two = requires(T t) {\n"
- " { t.foo() } -> std::same_as<Bar>;\n"
- " } && requires(T &&t) {\n"
- " { t.foo() } -> std::same_as<Bar &&>;\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "concept C = requires(T x) {\n"
- " { *x } -> std::convertible_to<typename T::inner>;\n"
- " { x + 1 } noexcept -> std::same_as<int>;\n"
- " { x * 1 } -> std::convertible_to<T>;\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept C = requires(T x) {\n"
- " {\n"
- " long_long_long_function_call(1, 2, 3, 4, 5)\n"
- " } -> long_long_concept_name<T>;\n"
- " {\n"
- " long_long_long_function_call(1, 2, 3, 4, 5)\n"
- " } noexcept -> long_long_concept_name<T>;\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T, typename U = T>\n"
- "concept Swappable = requires(T &&t, U &&u) {\n"
- " swap(std::forward<T>(t), std::forward<U>(u));\n"
- " swap(std::forward<U>(u), std::forward<T>(t));\n"
- " };",
- Style);
-
- verifyFormat("template <typename T, typename U>\n"
- "concept Common = requires(T &&t, U &&u) {\n"
- " typename CommonType<T, U>;\n"
- " { CommonType<T, U>(std::forward<T>(t)) };\n"
- " };",
- Style);
-
- verifyFormat("template <typename T, typename U>\n"
- "concept Common = requires(T &&t, U &&u) {\n"
- " typename CommonType<T, U>;\n"
- " { CommonType<T, U>{std::forward<T>(t)} };\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "concept C = requires(T t) {\n"
- " requires Bar<T> && Foo<T>;\n"
- " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept HasFoo = requires(T t) {\n"
- " { t.foo() };\n"
- " t.foo();\n"
- " };\n"
- "template <typename T>\n"
- "concept HasBar = requires(T t) {\n"
- " { t.bar() };\n"
- " t.bar();\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept Large = sizeof(T) > 10;");
-
- verifyFormat("template <typename T, typename U>\n"
- "concept FooableWith = requires(T t, U u) {\n"
- " typename T::foo_type;\n"
- " { t.foo(u) } -> typename T::foo_type;\n"
- " t++;\n"
- " };\n"
- "void doFoo(FooableWith<int> auto t) { t.foo(3); }",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept Context = is_specialization_of_v<context, T>;");
-
- verifyFormat("template <typename T>\n"
- "concept Node = std::is_object_v<T>;");
-
- verifyFormat("template <class T>\n"
- "concept integral = __is_integral(T);");
-
- verifyFormat("template <class T>\n"
- "concept is2D = __array_extent(T, 1) == 2;");
-
- verifyFormat("template <class T>\n"
- "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
-
- verifyFormat("template <class T, class T2>\n"
- "concept Same = __is_same_as<T, T2>;");
-
- verifyFormat(
- "template <class _InIt, class _OutIt>\n"
- "concept _Can_reread_dest =\n"
- " std::forward_iterator<_OutIt> &&\n"
- " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
-
- Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
-
- verifyFormat(
- "template <typename T>\n"
- "concept C = requires(T t) {\n"
- " requires Bar<T> && Foo<T>;\n"
- " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept HasFoo = requires(T t) {\n"
- " { t.foo() };\n"
- " t.foo();\n"
- " };\n"
- "template <typename T>\n"
- "concept HasBar = requires(T t) {\n"
- " { t.bar() };\n"
- " t.bar();\n"
- " };",
- Style);
-
- verifyFormat("template <typename T> concept True = true;", Style);
-
- verifyFormat("template <typename T>\n"
- "concept C = decltype([]() -> std::true_type { return {}; "
- "}())::value &&\n"
- " requires(T t) { t.bar(); } && sizeof(T) <= 8;",
- Style);
-
- verifyFormat("template <typename T>\n"
- "concept Semiregular =\n"
- " DefaultConstructible<T> && CopyConstructible<T> && "
- "CopyAssignable<T> &&\n"
- " requires(T a, std::size_t n) {\n"
- " requires Same<T *, decltype(&a)>;\n"
- " { a.~T() } noexcept;\n"
- " requires Same<T *, decltype(new T)>;\n"
- " requires Same<T *, decltype(new T[n])>;\n"
- " { delete new T; };\n"
- " { delete new T[n]; };\n"
- " };",
- Style);
-
- Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
-
- verifyFormat("template <typename T> concept C =\n"
- " requires(T t) {\n"
- " requires Bar<T> && Foo<T>;\n"
- " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
- " };",
- Style);
-
- verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
- " { t.foo() };\n"
- " t.foo();\n"
- " };\n"
- "template <typename T> concept HasBar = requires(T t) {\n"
- " { t.bar() };\n"
- " t.bar();\n"
- " };",
- Style);
-
- verifyFormat("template <typename T> concept True = true;", Style);
-
- verifyFormat(
- "template <typename T> concept C =\n"
- " decltype([]() -> std::true_type { return {}; }())::value &&\n"
- " requires(T t) { t.bar(); } && sizeof(T) <= 8;",
- Style);
-
- verifyFormat("template <typename T> concept Semiregular =\n"
- " DefaultConstructible<T> && CopyConstructible<T> && "
- "CopyAssignable<T> &&\n"
- " requires(T a, std::size_t n) {\n"
- " requires Same<T *, decltype(&a)>;\n"
- " { a.~T() } noexcept;\n"
- " requires Same<T *, decltype(new T)>;\n"
- " requires Same<T *, decltype(new T[n])>;\n"
- " { delete new T; };\n"
- " { delete new T[n]; };\n"
- " };",
- Style);
-
- // The following tests are invalid C++, we just want to make sure we don't
- // assert.
- verifyNoCrash("template <typename T>\n"
- "concept C = requires C2<T>;");
-
- verifyNoCrash("template <typename T>\n"
- "concept C = 5 + 4;");
-
- verifyNoCrash("template <typename T>\n"
- "concept C = class X;");
-
- verifyNoCrash("template <typename T>\n"
- "concept C = [] && true;");
-
- verifyNoCrash("template <typename T>\n"
- "concept C = [] && requires(T t) { typename T::size_type; };");
-}
-
-TEST_F(FormatTest, RequiresClausesPositions) {
- auto Style = getLLVMStyle();
- EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
- EXPECT_EQ(Style.IndentRequiresClause, true);
-
- // The default in LLVM style is REI_OuterScope, but these tests were written
- // when the default was REI_Keyword.
- Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "struct Bar;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "class Bar {\n"
- "public:\n"
- " Bar(T t);\n"
- " bool baz();\n"
- "};",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- " requires requires(T &&t) {\n"
- " typename T::I;\n"
- " requires(F<typename T::I> && std::trait<typename T::I>);\n"
- " }\n"
- "Bar(T) -> Bar<typename T::I>;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "constexpr T MyGlobal;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.baz() } -> std::same_as<bool>;\n"
- " requires std::same_as<T::Factor, int>;\n"
- " }\n"
- "inline int bar(T t) {\n"
- " return t.baz() ? T::Factor : 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "inline int bar(T t)\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.baz() } -> std::same_as<bool>;\n"
- " requires std::same_as<T::Factor, int>;\n"
- " }\n"
- "{\n"
- " return t.baz() ? T::Factor : 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires F<T>\n"
- "int bar(T t) {\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- " requires F<T>\n"
- "{\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int S::bar(T t) &&\n"
- " requires F<T>\n"
- "{\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- " requires F<T>;",
- Style);
-
- Style.IndentRequiresClause = false;
- verifyFormat("template <typename T>\n"
- "requires F<T>\n"
- "int bar(T t) {\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int S::bar(T t) &&\n"
- "requires F<T>\n"
- "{\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- "requires F<T>\n"
- "{\n"
- " return 5;\n"
- "}",
- Style);
-
- Style.RequiresClausePosition = FormatStyle::RCPS_OwnLineWithBrace;
- Style.IndentRequiresClause = true;
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "struct Bar;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "class Bar {\n"
- "public:\n"
- " Bar(T t);\n"
- " bool baz();\n"
- "};",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- " requires requires(T &&t) {\n"
- " typename T::I;\n"
- " requires(F<typename T::I> && std::trait<typename T::I>);\n"
- " }\n"
- "Bar(T) -> Bar<typename T::I>;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires(Foo<T> && std::trait<T>)\n"
- "constexpr T MyGlobal;",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.baz() } -> std::same_as<bool>;\n"
- " requires std::same_as<T::Factor, int>;\n"
- " }\n"
- "inline int bar(T t) {\n"
- " return t.baz() ? T::Factor : 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "inline int bar(T t)\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.baz() } -> std::same_as<bool>;\n"
- " requires std::same_as<T::Factor, int>;\n"
- " } {\n"
- " return t.baz() ? T::Factor : 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires F<T>\n"
- "int bar(T t) {\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- " requires F<T> {\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int S::bar(T t) &&\n"
- " requires F<T> {\n"
- " return 5;\n"
- "}",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- " requires F<T>;",
- Style);
-
- verifyFormat("template <typename T>\n"
- "int bar(T t)\n"
- " requires F<T> {}",
- Style);
-
- Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
- Style.IndentRequiresClause = false;
- verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
- "template <typename T> requires Foo<T> void bar() {}\n"
- "template <typename T> void bar() requires Foo<T> {}\n"
- "template <typename T> void bar() requires Foo<T>;\n"
- "template <typename T> void S::bar() && requires Foo<T> {}\n"
- "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
- Style);
-
- auto ColumnStyle = Style;
- ColumnStyle.ColumnLimit = 40;
- verifyFormat("template <typename AAAAAAA>\n"
- "requires Foo<T> struct Bar {};\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<T> void bar() {}\n"
- "template <typename AAAAAAA>\n"
- "void bar() requires Foo<T> {}\n"
- "template <typename T>\n"
- "void S::bar() && requires Foo<T> {}\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<T> Baz(T) -> Baz<T>;",
- ColumnStyle);
-
- verifyFormat("template <typename T>\n"
- "requires Foo<AAAAAAA> struct Bar {};\n"
- "template <typename T>\n"
- "requires Foo<AAAAAAA> void bar() {}\n"
- "template <typename T>\n"
- "void bar() requires Foo<AAAAAAA> {}\n"
- "template <typename T>\n"
- "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
- ColumnStyle);
-
- verifyFormat("template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "struct Bar {};\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "void bar() {}\n"
- "template <typename AAAAAAA>\n"
- "void bar()\n"
- " requires Foo<AAAAAAAAAAAAAAAA> {}\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "Bar(T) -> Bar<T>;",
- ColumnStyle);
-
- Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
- ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
-
- verifyFormat("template <typename T>\n"
- "requires Foo<T> struct Bar {};\n"
- "template <typename T>\n"
- "requires Foo<T> void bar() {}\n"
- "template <typename T>\n"
- "void bar()\n"
- "requires Foo<T> {}\n"
- "template <typename T>\n"
- "void bar()\n"
- "requires Foo<T>;\n"
- "template <typename T>\n"
- "void S::bar() &&\n"
- "requires Foo<T> {}\n"
- "template <typename T>\n"
- "requires Foo<T> Bar(T) -> Bar<T>;",
- Style);
-
- verifyFormat("template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "struct Bar {};\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "void bar() {}\n"
- "template <typename AAAAAAA>\n"
- "void bar()\n"
- "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "Bar(T) -> Bar<T>;",
- ColumnStyle);
-
- Style.IndentRequiresClause = true;
- ColumnStyle.IndentRequiresClause = true;
-
- verifyFormat("template <typename T>\n"
- " requires Foo<T> struct Bar {};\n"
- "template <typename T>\n"
- " requires Foo<T> void bar() {}\n"
- "template <typename T>\n"
- "void bar()\n"
- " requires Foo<T> {}\n"
- "template <typename T>\n"
- "void S::bar() &&\n"
- " requires Foo<T> {}\n"
- "template <typename T>\n"
- " requires Foo<T> Bar(T) -> Bar<T>;",
- Style);
-
- verifyFormat("template <typename AAAAAAA>\n"
- " requires Foo<AAAAAAAAAAAAAAAA>\n"
- "struct Bar {};\n"
- "template <typename AAAAAAA>\n"
- " requires Foo<AAAAAAAAAAAAAAAA>\n"
- "void bar() {}\n"
- "template <typename AAAAAAA>\n"
- "void bar()\n"
- " requires Foo<AAAAAAAAAAAAAAAA> {}\n"
- "template <typename AAAAAAA>\n"
- " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
- "template <typename AAAAAAA>\n"
- " requires Foo<AAAAAAAAAAAAAAAA>\n"
- "Bar(T) -> Bar<T>;",
- ColumnStyle);
-
- Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
- ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
-
- verifyFormat("template <typename T> requires Foo<T>\n"
- "struct Bar {};\n"
- "template <typename T> requires Foo<T>\n"
- "void bar() {}\n"
- "template <typename T>\n"
- "void bar() requires Foo<T>\n"
- "{}\n"
- "template <typename T> void bar() requires Foo<T>;\n"
- "template <typename T>\n"
- "void S::bar() && requires Foo<T>\n"
- "{}\n"
- "template <typename T> requires Foo<T>\n"
- "Bar(T) -> Bar<T>;",
- Style);
-
- verifyFormat("template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "struct Bar {};\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "void bar() {}\n"
- "template <typename AAAAAAA>\n"
- "void bar()\n"
- " requires Foo<AAAAAAAAAAAAAAAA>\n"
- "{}\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAA>\n"
- "Bar(T) -> Bar<T>;\n"
- "template <typename AAAAAAA>\n"
- "requires Foo<AAAAAAAAAAAAAAAA>\n"
- "Bar(T) -> Bar<T>;",
- ColumnStyle);
-}
-
-TEST_F(FormatTest, RequiresClauses) {
- verifyFormat("struct [[nodiscard]] zero_t {\n"
- " template <class T>\n"
- " requires requires { number_zero_v<T>; }\n"
- " [[nodiscard]] constexpr operator T() const {\n"
- " return number_zero_v<T>;\n"
- " }\n"
- "};");
-
- verifyFormat("template <class T>\n"
- " requires(std::same_as<int, T>)\n"
- "decltype(auto) fun() {}");
-
- auto Style = getLLVMStyle();
-
- verifyFormat(
- "template <typename T>\n"
- " requires is_default_constructible_v<hash<T>> and\n"
- " is_copy_constructible_v<hash<T>> and\n"
- " is_move_constructible_v<hash<T>> and\n"
- " is_copy_assignable_v<hash<T>> and "
- "is_move_assignable_v<hash<T>> and\n"
- " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
- " is_callable_v<hash<T>(T)> and\n"
- " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
- " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
- " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
- "struct S {};",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat(
- "template <typename T>\n"
- " requires is_default_constructible_v<hash<T>>\n"
- " and is_copy_constructible_v<hash<T>>\n"
- " and is_move_constructible_v<hash<T>>\n"
- " and is_copy_assignable_v<hash<T>> and "
- "is_move_assignable_v<hash<T>>\n"
- " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
- " and is_callable_v<hash<T>(T)>\n"
- " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
- " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
- " and is_same_v<size_t, decltype(hash<T>(declval<const T "
- "&>()))>\n"
- "struct S {};",
- Style);
-
- Style = getLLVMStyle();
- Style.ConstructorInitializerIndentWidth = 4;
- Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
- Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
- verifyFormat("constexpr Foo(Foo const &other)\n"
- " requires std::is_copy_constructible<T>\n"
- " : value{other.value} {\n"
- " do_magic();\n"
- " do_more_magic();\n"
- "}",
- Style);
-
- // Not a clause, but we once hit an assert.
- verifyFormat("#if 0\n"
- "#else\n"
- "foo();\n"
- "#endif\n"
- "bar(requires);");
-
- verifyNoCrash("template <class T>\n"
- " requires(requires { std::declval<T>()");
-}
-
-TEST_F(FormatTest, RequiresExpressionIndentation) {
- auto Style = getLLVMStyle();
- EXPECT_EQ(Style.RequiresExpressionIndentation, FormatStyle::REI_OuterScope);
-
- verifyFormat("template <typename T>\n"
- "concept C = requires(T t) {\n"
- " typename T::value;\n"
- " requires requires(typename T::value v) {\n"
- " { t == v } -> std::same_as<bool>;\n"
- " };\n"
- "};",
- Style);
-
- verifyFormat("template <typename T>\n"
- "void bar(T)\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.foo() } -> std::same_as<int>;\n"
- " } && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " --t;\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires Foo<T> &&\n"
- " requires(T t) {\n"
- " { t.foo() } -> std::same_as<int>;\n"
- " } && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " --t;\n"
- " }\n"
- "void bar(T);",
- Style);
-
- verifyFormat("template <typename T> void f() {\n"
- " if constexpr (requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " }) {\n"
- " }\n"
- "}",
- Style);
-
- verifyFormat("template <typename T> void f() {\n"
- " if constexpr (condition && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " }) {\n"
- " }\n"
- "}",
- Style);
-
- verifyFormat("template <typename T> struct C {\n"
- " void f()\n"
- " requires requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " };\n"
- "};",
- Style);
-
- Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
-
- verifyFormat("template <typename T>\n"
- "concept C = requires(T t) {\n"
- " typename T::value;\n"
- " requires requires(typename T::value v) {\n"
- " { t == v } -> std::same_as<bool>;\n"
- " };\n"
- " };",
- Style);
-
- verifyFormat(
- "template <typename T>\n"
- "void bar(T)\n"
- " requires Foo<T> && requires(T t) {\n"
- " { t.foo() } -> std::same_as<int>;\n"
- " } && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " --t;\n"
- " };",
- Style);
-
- verifyFormat("template <typename T>\n"
- " requires Foo<T> &&\n"
- " requires(T t) {\n"
- " { t.foo() } -> std::same_as<int>;\n"
- " } && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " --t;\n"
- " }\n"
- "void bar(T);",
- Style);
-
- verifyFormat("template <typename T> void f() {\n"
- " if constexpr (requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " }) {\n"
- " }\n"
- "}",
- Style);
-
- verifyFormat(
- "template <typename T> void f() {\n"
- " if constexpr (condition && requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " }) {\n"
- " }\n"
- "}",
- Style);
-
- verifyFormat("template <typename T> struct C {\n"
- " void f()\n"
- " requires requires(T t) {\n"
- " { t.bar() } -> std::same_as<bool>;\n"
- " };\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, StatementAttributeLikeMacros) {
- FormatStyle Style = getLLVMStyle();
- StringRef Source = "void Foo::slot() {\n"
- " unsigned char MyChar = 'x';\n"
- " emit signal(MyChar);\n"
- " Q_EMIT signal(MyChar);\n"
- "}";
-
- verifyFormat(Source, Style);
-
- Style.AlignConsecutiveDeclarations.Enabled = true;
- verifyFormat("void Foo::slot() {\n"
- " unsigned char MyChar = 'x';\n"
- " emit signal(MyChar);\n"
- " Q_EMIT signal(MyChar);\n"
- "}",
- Source, Style);
-
- Style.StatementAttributeLikeMacros.push_back("emit");
- verifyFormat(Source, Style);
-
- Style.StatementAttributeLikeMacros = {};
- verifyFormat("void Foo::slot() {\n"
- " unsigned char MyChar = 'x';\n"
- " emit signal(MyChar);\n"
- " Q_EMIT signal(MyChar);\n"
- "}",
- Source, Style);
-}
-
-TEST_F(FormatTest, IndentAccessModifiers) {
- FormatStyle Style = getLLVMStyle();
- Style.IndentAccessModifiers = true;
- // Members are *two* levels below the record;
- // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
- verifyFormat("class C {\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("union C {\n"
- " int i;\n"
- " unsigned u;\n"
- "};",
- Style);
- // Access modifiers should be indented one level below the record.
- verifyFormat("class C {\n"
- " public:\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("class C {\n"
- " public /* comment */:\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("struct S {\n"
- " private:\n"
- " class C {\n"
- " int j;\n"
- "\n"
- " public:\n"
- " C();\n"
- " };\n"
- "\n"
- " public:\n"
- " int i;\n"
- "};",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
- verifyFormat("struct S\n"
- " {\n"
- " public:\n"
- " int i;\n"
- "\n"
- " private:\n"
- " class C\n"
- " {\n"
- " private:\n"
- " int j;\n"
- " };\n"
- " };",
- Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Attach;
- // Enumerations are not records and should be unaffected.
- Style.AllowShortEnumsOnASingleLine = false;
- verifyFormat("enum class E {\n"
- " A,\n"
- " B\n"
- "};",
- Style);
- // Test with a different indentation width;
- // also proves that the result is Style.AccessModifierOffset agnostic.
- Style.IndentWidth = 3;
- verifyFormat("class C {\n"
- " public:\n"
- " int i;\n"
- "};",
- Style);
- verifyFormat("class C {\n"
- " public /**/:\n"
- " int i;\n"
- "};",
- Style);
- Style.AttributeMacros.push_back("FOO");
- verifyFormat("class C {\n"
- " FOO public:\n"
- " int i;\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, LimitlessStringsAndComments) {
- auto Style = getLLVMStyleWithColumns(0);
- constexpr StringRef Code(
- "/**\n"
- " * This is a multiline comment with quite some long lines, at least for "
- "the LLVM Style.\n"
- " * We will redo this with strings and line comments. Just to check if "
- "everything is working.\n"
- " */\n"
- "bool foo() {\n"
- " /* Single line multi line comment. */\n"
- " const std::string String = \"This is a multiline string with quite "
- "some long lines, at least for the LLVM Style.\"\n"
- " \"We already did it with multi line "
- "comments, and we will do it with line comments. Just to check if "
- "everything is working.\";\n"
- " // This is a line comment (block) with quite some long lines, at "
- "least for the LLVM Style.\n"
- " // We already did this with multi line comments and strings. Just to "
- "check if everything is working.\n"
- " const std::string SmallString = \"Hello World\";\n"
- " // Small line comment\n"
- " return String.size() > SmallString.size();\n"
- "}");
- verifyNoChange(Code, Style);
-}
-
-TEST_F(FormatTest, FormatDecayCopy) {
- // error cases from unit tests
- verifyFormat("foo(auto())");
- verifyFormat("foo(auto{})");
- verifyFormat("foo(auto({}))");
- verifyFormat("foo(auto{{}})");
-
- verifyFormat("foo(auto(1))");
- verifyFormat("foo(auto{1})");
- verifyFormat("foo(new auto(1))");
- verifyFormat("foo(new auto{1})");
- verifyFormat("decltype(auto(1)) x;");
- verifyFormat("decltype(auto{1}) x;");
- verifyFormat("auto(x);");
- verifyFormat("auto{x};");
- verifyFormat("new auto{x};");
- verifyFormat("auto{x} = y;");
- verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
- // the user's own fault
- verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
- // clearly the user's own fault
- verifyFormat("auto (*p)() = f;");
-}
-
-TEST_F(FormatTest, Cpp20ModulesSupport) {
- FormatStyle Style = getLLVMStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
- Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
-
- verifyFormat("export import foo;", Style);
- verifyFormat("export import foo:bar;", Style);
- verifyFormat("export import foo.bar;", Style);
- verifyFormat("export import foo.bar:baz;", Style);
- verifyFormat("export import :bar;", Style);
- verifyFormat("export module foo:bar;", Style);
- verifyFormat("export module foo;", Style);
- verifyFormat("export module foo.bar;", Style);
- verifyFormat("export module foo.bar:baz;", Style);
- verifyFormat("export import <string_view>;", Style);
- verifyFormat("export import <Foo/Bar>;", Style);
-
- verifyFormat("export type_name var;", Style);
- verifyFormat("template <class T> export using A = B<T>;", Style);
- verifyFormat("export using A = B;", Style);
- verifyFormat("export int func() {\n"
- " foo();\n"
- "}",
- Style);
- verifyFormat("export struct {\n"
- " int foo;\n"
- "};",
- Style);
- verifyFormat("export {\n"
- " int foo;\n"
- "};",
- Style);
- verifyFormat("export export char const *hello() { return \"hello\"; }");
-
- verifyFormat("import bar;", Style);
- verifyFormat("import foo.bar;", Style);
- verifyFormat("import foo:bar;", Style);
- verifyFormat("import :bar;", Style);
- verifyFormat("import /* module partition */ :bar;", Style);
- verifyFormat("import <ctime>;", Style);
- verifyFormat("import \"header\";", Style);
-
- verifyFormat("module foo;", Style);
- verifyFormat("module foo:bar;", Style);
- verifyFormat("module foo.bar;", Style);
- verifyFormat("module;", Style);
-
- verifyFormat("export namespace hi {\n"
- "const char *sayhi();\n"
- "}",
- Style);
-
- verifyFormat("module :private;", Style);
- verifyFormat("import <foo/bar.h>;", Style);
- verifyFormat("import foo...bar;", Style);
- verifyFormat("import ..........;", Style);
- verifyFormat("module foo:private;", Style);
- verifyFormat("import a", Style);
- verifyFormat("module a", Style);
- verifyFormat("export import a", Style);
- verifyFormat("export module a", Style);
-
- verifyFormat("import", Style);
- verifyFormat("module", Style);
- verifyFormat("export", Style);
-
- verifyFormat("import /* not keyword */ = val ? 2 : 1;");
- verifyFormat("_world->import<engine_module>();");
-}
-
-TEST_F(FormatTest, CoroutineForCoawait) {
- FormatStyle Style = getLLVMStyle();
- verifyFormat("for co_await (auto x : range())\n ;");
- verifyFormat("for (auto i : arr) {\n"
- "}",
- Style);
- verifyFormat("for co_await (auto i : arr) {\n"
- "}",
- Style);
- verifyFormat("for co_await (auto i : foo(T{})) {\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, CoroutineCoAwait) {
- verifyFormat("int x = co_await foo();");
- verifyFormat("int x = (co_await foo());");
- verifyFormat("co_await (42);");
- verifyFormat("void operator co_await(int);");
- verifyFormat("void operator co_await(a);");
- verifyFormat("co_await a;");
- verifyFormat("co_await missing_await_resume{};");
- verifyFormat("co_await a; // comment");
- verifyFormat("void test0() { co_await a; }");
- verifyFormat("co_await co_await co_await foo();");
- verifyFormat("co_await foo().bar();");
- verifyFormat("co_await [this]() -> Task { co_return x; }");
- verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
- "foo(); }(x, y);");
-
- FormatStyle Style = getLLVMStyleWithColumns(40);
- verifyFormat("co_await [this](int a, int b) -> Task {\n"
- " co_return co_await foo();\n"
- "}(x, y);",
- Style);
- verifyFormat("co_await;");
-}
-
-TEST_F(FormatTest, CoroutineCoYield) {
- verifyFormat("int x = co_yield foo();");
- verifyFormat("int x = (co_yield foo());");
- verifyFormat("co_yield (42);");
- verifyFormat("co_yield {42};");
- verifyFormat("co_yield 42;");
- verifyFormat("co_yield n++;");
- verifyFormat("co_yield ++n;");
- verifyFormat("co_yield;");
-}
-
-TEST_F(FormatTest, CoroutineCoReturn) {
- verifyFormat("co_return (42);");
- verifyFormat("co_return;");
- verifyFormat("co_return {};");
- verifyFormat("co_return x;");
- verifyFormat("co_return co_await foo();");
- verifyFormat("co_return co_yield foo();");
-}
-
-TEST_F(FormatTest, EmptyShortBlock) {
- auto Style = getLLVMStyle();
- Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
-
- verifyFormat("try {\n"
- " doA();\n"
- "} catch (Exception &e) {\n"
- " e.printStackTrace();\n"
- "}",
- Style);
-
- verifyFormat("try {\n"
- " doA();\n"
- "} catch (Exception &e) {}",
- Style);
-}
-
-TEST_F(FormatTest, ShortTemplatedArgumentLists) {
- auto Style = getLLVMStyle();
-
- verifyFormat("template <> struct S : Template<int (*)[]> {};", Style);
- verifyFormat("template <> struct S : Template<int (*)[10]> {};", Style);
- verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
- verifyFormat("struct Y<[] { return 0; }> {};", Style);
-
- verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
- verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
-}
-
-TEST_F(FormatTest, MultilineLambdaInConditional) {
- auto Style = getLLVMStyleWithColumns(70);
- verifyFormat("auto aLengthyIdentifier = oneExpressionSoThatWeBreak ? []() {\n"
- " ;\n"
- " return 5;\n"
- "}()\n"
- " : 2;",
- Style);
- verifyFormat(
- "auto aLengthyIdentifier = oneExpressionSoThatWeBreak ? 2 : []() {\n"
- " ;\n"
- " return 5;\n"
- "}();",
- Style);
-
- Style = getLLVMStyleWithColumns(60);
- verifyFormat("auto aLengthyIdentifier = oneExpressionSoThatWeBreak\n"
- " ? []() {\n"
- " ;\n"
- " return 5;\n"
- " }()\n"
- " : 2;",
- Style);
- verifyFormat("auto aLengthyIdentifier =\n"
- " oneExpressionSoThatWeBreak ? 2 : []() {\n"
- " ;\n"
- " return 5;\n"
- " }();",
- Style);
-
- Style = getLLVMStyleWithColumns(40);
- verifyFormat("auto aLengthyIdentifier =\n"
- " oneExpressionSoThatWeBreak ? []() {\n"
- " ;\n"
- " return 5;\n"
- " }()\n"
- " : 2;",
- Style);
- verifyFormat("auto aLengthyIdentifier =\n"
- " oneExpressionSoThatWeBreak\n"
- " ? 2\n"
- " : []() {\n"
- " ;\n"
- " return 5;\n"
- " };",
- Style);
-}
-
-TEST_F(FormatTest, UnderstandsDigraphs) {
- verifyFormat("int arr<:5:> = {};");
- verifyFormat("int arr[5] = <%%>;");
- verifyFormat("int arr<:::qualified_variable:> = {};");
- verifyFormat("int arr[::qualified_variable] = <%%>;");
- verifyFormat("%:include <header>");
- verifyFormat("%:define A x##y");
- verifyFormat("#define A x%:%:y");
-}
-
-TEST_F(FormatTest, FormatsVariableTemplates) {
- verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
- verifyFormat("template <typename T> "
- "inline bool var = is_integral_v<T> && is_signed_v<T>;");
-}
-
-TEST_F(FormatTest, RemoveSemicolon) {
- FormatStyle Style = getLLVMStyle();
- Style.RemoveSemicolon = true;
-
- verifyFormat("int max(int a, int b) { return a > b ? a : b; }",
- "int max(int a, int b) { return a > b ? a : b; };", Style);
-
- verifyFormat("int max(int a, int b) { return a > b ? a : b; }",
- "int max(int a, int b) { return a > b ? a : b; };;", Style);
-
- verifyFormat("class Foo {\n"
- " int getSomething() const { return something; }\n"
- "};",
- "class Foo {\n"
- " int getSomething() const { return something; };\n"
- "};",
- Style);
-
- verifyFormat("class Foo {\n"
- " int getSomething() const { return something; }\n"
- "};",
- "class Foo {\n"
- " int getSomething() const { return something; };;\n"
- "};",
- Style);
-
- verifyFormat("for (;;) {\n"
- "}",
- Style);
-
- verifyFormat("class [[deprecated(\"\")]] C {\n"
- " int i;\n"
- "};",
- Style);
-
- verifyFormat("struct EXPORT_MACRO [[nodiscard]] C {\n"
- " int i;\n"
- "};",
- Style);
-
- verifyIncompleteFormat("class C final [[deprecated(l]] {});", Style);
-
- verifyFormat("void main() {}", "void main() {};", Style);
-
- verifyFormat("struct Foo {\n"
- " Foo() {}\n"
- " ~Foo() {}\n"
- "};",
- "struct Foo {\n"
- " Foo() {};\n"
- " ~Foo() {};\n"
- "};",
- Style);
-
-// We can't (and probably shouldn't) support the following.
-#if 0
- verifyFormat("void foo() {} //\n"
- "int bar;",
- "void foo() {}; //\n"
- "; int bar;",
- Style);
-#endif
-
- verifyFormat("auto sgf = [] {\n"
- " ogl = {\n"
- " a, b, c, d, e,\n"
- " };\n"
- "};",
- Style);
-
- Style.TypenameMacros.push_back("STRUCT");
- verifyFormat("STRUCT(T, B) { int i; };", Style);
-}
-
-TEST_F(FormatTest, EnumTrailingComma) {
- constexpr StringRef Code("enum : int { /**/ };\n"
- "enum {\n"
- " a,\n"
- " b,\n"
- " c, //\n"
- "};\n"
- "enum Color { red, green, blue /**/ };");
- verifyFormat(Code);
-
- auto Style = getLLVMStyle();
- Style.EnumTrailingComma = FormatStyle::ETC_Insert;
- verifyFormat("enum : int { /**/ };\n"
- "enum {\n"
- " a,\n"
- " b,\n"
- " c, //\n"
- "};\n"
- "enum Color { red, green, blue, /**/ };",
- Code, Style);
-
- Style.EnumTrailingComma = FormatStyle::ETC_Remove;
- verifyFormat("enum : int { /**/ };\n"
- "enum {\n"
- " a,\n"
- " b,\n"
- " c //\n"
- "};\n"
- "enum Color { red, green, blue /**/ };",
- Code, Style);
-
- EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
- Style.AllowShortEnumsOnASingleLine = false;
-
- constexpr StringRef Input("enum {\n"
- " //\n"
- " a,\n"
- " /**/\n"
- " b,\n"
- "};");
- verifyFormat(Input, Input, Style, {tooling::Range(12, 3)}); // line 3
- verifyFormat("enum {\n"
- " //\n"
- " a,\n"
- " /**/\n"
- " b\n"
- "};",
- Input, Style, {tooling::Range(24, 3)}); // line 5
-
- Style.EnumTrailingComma = FormatStyle::ETC_Insert;
- verifyFormat("enum class MyEnum_E {\n"
- " MY_ENUM = 0U,\n"
- "};",
- "enum class MyEnum_E {\n"
- " MY_ENUM = 0U\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, BreakAfterAttributes) {
- constexpr StringRef Code("[[maybe_unused]] const int i;\n"
- "[[foo([[]])]] [[maybe_unused]]\n"
- "int j;\n"
- "[[maybe_unused]]\n"
- "foo<int> k;\n"
- "[[nodiscard]] inline int f(int &i);\n"
- "[[foo([[]])]] [[nodiscard]]\n"
- "int g(int &i);\n"
- "[[nodiscard]]\n"
- "inline int f(int &i) {\n"
- " i = 1;\n"
- " return 0;\n"
- "}\n"
- "[[foo([[]])]] [[nodiscard]] int g(int &i) {\n"
- " i = 0;\n"
- " return 1;\n"
- "}");
-
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.BreakAfterAttributes, FormatStyle::ABS_Leave);
- verifyNoChange(Code, Style);
-
- Style.BreakAfterAttributes = FormatStyle::ABS_LeaveAll;
- verifyNoChange("[[deprecated(\"Don't use this version\")]]\n"
- "[[nodiscard]]\n"
- "bool foo() {\n"
- " return true;\n"
- "}\n"
- "\n"
- "[[deprecated(\"Don't use this version\")]]\n"
- "[[nodiscard]] bool bar() {\n"
- " return true;\n"
- "}",
- Style);
-
- Style.BreakAfterAttributes = FormatStyle::ABS_Never;
- verifyFormat("[[maybe_unused]] const int i;\n"
- "[[foo([[]])]] [[maybe_unused]] int j;\n"
- "[[maybe_unused]] foo<int> k;\n"
- "[[nodiscard]] inline int f(int &i);\n"
- "[[foo([[]])]] [[nodiscard]] int g(int &i);\n"
- "[[nodiscard]] inline int f(int &i) {\n"
- " i = 1;\n"
- " return 0;\n"
- "}\n"
- "[[foo([[]])]] [[nodiscard]] int g(int &i) {\n"
- " i = 0;\n"
- " return 1;\n"
- "}",
- Code, Style);
-
- Style.BreakAfterAttributes = FormatStyle::ABS_Always;
- verifyFormat("[[maybe_unused]]\n"
- "const int i;\n"
- "[[foo([[]])]] [[maybe_unused]]\n"
- "int j;\n"
- "[[maybe_unused]]\n"
- "foo<int> k;\n"
- "[[nodiscard]]\n"
- "inline int f(int &i);\n"
- "[[foo([[]])]] [[nodiscard]]\n"
- "int g(int &i);\n"
- "[[nodiscard]]\n"
- "inline int f(int &i) {\n"
- " i = 1;\n"
- " return 0;\n"
- "}\n"
- "[[foo([[]])]] [[nodiscard]]\n"
- "int g(int &i) {\n"
- " i = 0;\n"
- " return 1;\n"
- "}",
- Code, Style);
-
- constexpr StringRef CtrlStmtCode("[[likely]] if (a)\n"
- " f();\n"
- "else\n"
- " g();\n"
- "[[foo([[]])]]\n"
- "switch (b) {\n"
- "[[unlikely]] case 1:\n"
- " ++b;\n"
- " break;\n"
- "[[likely]]\n"
- "default:\n"
- " return;\n"
- "}\n"
- "[[unlikely]] for (; c > 0; --c)\n"
- " h();\n"
- "[[likely]]\n"
- "while (d > 0)\n"
- " --d;");
-
- Style.BreakAfterAttributes = FormatStyle::ABS_Leave;
- verifyNoChange(CtrlStmtCode, Style);
-
- Style.BreakAfterAttributes = FormatStyle::ABS_Never;
- verifyFormat("[[likely]] if (a)\n"
- " f();\n"
- "else\n"
- " g();\n"
- "[[foo([[]])]] switch (b) {\n"
- "[[unlikely]] case 1:\n"
- " ++b;\n"
- " break;\n"
- "[[likely]] default:\n"
- " return;\n"
- "}\n"
- "[[unlikely]] for (; c > 0; --c)\n"
- " h();\n"
- "[[likely]] while (d > 0)\n"
- " --d;",
- CtrlStmtCode, Style);
-
- Style.BreakAfterAttributes = FormatStyle::ABS_Always;
- verifyFormat("[[likely]]\n"
- "if (a)\n"
- " f();\n"
- "else\n"
- " g();\n"
- "[[foo([[]])]]\n"
- "switch (b) {\n"
- "[[unlikely]]\n"
- "case 1:\n"
- " ++b;\n"
- " break;\n"
- "[[likely]]\n"
- "default:\n"
- " return;\n"
- "}\n"
- "[[unlikely]]\n"
- "for (; c > 0; --c)\n"
- " h();\n"
- "[[likely]]\n"
- "while (d > 0)\n"
- " --d;",
- CtrlStmtCode, Style);
-
- verifyFormat("[[nodiscard]]\n"
- "operator bool();\n"
- "[[nodiscard]]\n"
- "operator bool() {\n"
- " return true;\n"
- "}",
- "[[nodiscard]] operator bool();\n"
- "[[nodiscard]] operator bool() { return true; }",
- Style);
-
- constexpr StringRef CtorDtorCode("struct Foo {\n"
- " [[deprecated]] Foo();\n"
- " [[deprecated]] Foo() {}\n"
- " [[deprecated]] ~Foo();\n"
- " [[deprecated]] ~Foo() {}\n"
- " [[deprecated]] void f();\n"
- " [[deprecated]] void f() {}\n"
- "};\n"
- "[[deprecated]] Bar::Bar() {}\n"
- "[[deprecated]] Bar::~Bar() {}\n"
- "[[deprecated]] void g() {}");
- verifyFormat("struct Foo {\n"
- " [[deprecated]]\n"
- " Foo();\n"
- " [[deprecated]]\n"
- " Foo() {}\n"
- " [[deprecated]]\n"
- " ~Foo();\n"
- " [[deprecated]]\n"
- " ~Foo() {}\n"
- " [[deprecated]]\n"
- " void f();\n"
- " [[deprecated]]\n"
- " void f() {}\n"
- "};\n"
- "[[deprecated]]\n"
- "Bar::Bar() {}\n"
- "[[deprecated]]\n"
- "Bar::~Bar() {}\n"
- "[[deprecated]]\n"
- "void g() {}",
- CtorDtorCode, Style);
-
- Style.BreakBeforeBraces = FormatStyle::BS_Linux;
- verifyFormat("struct Foo {\n"
- " [[deprecated]]\n"
- " Foo();\n"
- " [[deprecated]]\n"
- " Foo()\n"
- " {\n"
- " }\n"
- " [[deprecated]]\n"
- " ~Foo();\n"
- " [[deprecated]]\n"
- " ~Foo()\n"
- " {\n"
- " }\n"
- " [[deprecated]]\n"
- " void f();\n"
- " [[deprecated]]\n"
- " void f()\n"
- " {\n"
- " }\n"
- "};\n"
- "[[deprecated]]\n"
- "Bar::Bar()\n"
- "{\n"
- "}\n"
- "[[deprecated]]\n"
- "Bar::~Bar()\n"
- "{\n"
- "}\n"
- "[[deprecated]]\n"
- "void g()\n"
- "{\n"
- "}",
- CtorDtorCode, Style);
-
- verifyFormat("struct Foo {\n"
- " [[maybe_unused]]\n"
- " void operator+();\n"
- "};\n"
- "[[nodiscard]]\n"
- "Foo &operator-(Foo &);",
- Style);
-
- Style.ReferenceAlignment = FormatStyle::RAS_Left;
- verifyFormat("[[nodiscard]]\n"
- "Foo& operator-(Foo&);",
- Style);
-
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
- verifyFormat("[[deprecated]]\n"
- "void f() = delete;",
- Style);
-}
-
-TEST_F(FormatTest, InsertNewlineAtEOF) {
- FormatStyle Style = getLLVMStyle();
- Style.InsertNewlineAtEOF = true;
-
- verifyNoChange("int i;\n", Style);
- verifyFormat("int i;\n", "int i;", Style);
-
- constexpr StringRef Code("namespace {\n"
- "int i;\n"
- "} // namespace");
- verifyFormat(Code.str() + '\n', Code, Style,
- {tooling::Range(19, 13)}); // line 3
-}
-
-TEST_F(FormatTest, KeepEmptyLinesAtEOF) {
- FormatStyle Style = getLLVMStyle();
- Style.KeepEmptyLines.AtEndOfFile = true;
-
- constexpr StringRef Code("int i;\n\n");
- verifyNoChange(Code, Style);
- verifyFormat(Code, "int i;\n\n\n", Style);
-}
-
-TEST_F(FormatTest, SpaceAfterUDL) {
- verifyFormat("auto c = (4s).count();");
- verifyFormat("auto x = 5s .count() == 5;");
-}
-
-TEST_F(FormatTest, InterfaceAsClassMemberName) {
- verifyFormat("class Foo {\n"
- " int interface;\n"
- " Foo::Foo(int iface) : interface{iface} {}\n"
- "}");
-}
-
-TEST_F(FormatTest, PreprocessorOverlappingRegions) {
- verifyFormat("#ifdef\n\n"
- "#else\n"
- "#endif",
- "#ifdef \n"
- " \n"
- "\n"
- "#else \n"
- "#endif ",
- getGoogleStyle());
-}
-
-TEST_F(FormatTest, RemoveParentheses) {
- FormatStyle Style = getLLVMStyle();
- EXPECT_EQ(Style.RemoveParentheses, FormatStyle::RPS_Leave);
-
- Style.RemoveParentheses = FormatStyle::RPS_MultipleParentheses;
- verifyFormat("#define Foo(...) foo((__VA_ARGS__))", Style);
- verifyFormat("int x __attribute__((aligned(16))) = 0;", Style);
- verifyFormat("decltype((foo->bar)) baz;", Style);
- verifyFormat("class __declspec(dllimport) X {};",
- "class __declspec((dllimport)) X {};", Style);
- verifyFormat("int x = (({ 0; }));", "int x = ((({ 0; })));", Style);
- verifyFormat("while (a)\n"
- " b;",
- "while (((a)))\n"
- " b;",
- Style);
- verifyFormat("while ((a = b))\n"
- " c;",
- "while (((a = b)))\n"
- " c;",
- Style);
- verifyFormat("if (a)\n"
- " b;",
- "if (((a)))\n"
- " b;",
- Style);
- verifyFormat("if constexpr ((a = b))\n"
- " c;",
- "if constexpr (((a = b)))\n"
- " c;",
- Style);
- verifyFormat("if (({ a; }))\n"
- " b;",
- "if ((({ a; })))\n"
- " b;",
- Style);
- verifyFormat("static_assert((std::is_constructible_v<T, Args &&> && ...));",
- "static_assert(((std::is_constructible_v<T, Args &&> && ...)));",
- Style);
- verifyFormat("foo((a, b));", "foo(((a, b)));", Style);
- verifyFormat("foo((a, b));", "foo(((a), b));", Style);
- verifyFormat("foo((a, b));", "foo((a, (b)));", Style);
- verifyFormat("foo((a, b, c));", "foo((a, ((b)), c));", Style);
- verifyFormat("(..., (hash_a = hash_combine(hash_a, hash_b)));",
- "(..., ((hash_a = hash_combine(hash_a, hash_b))));", Style);
- verifyFormat("((hash_a = hash_combine(hash_a, hash_b)), ...);",
- "(((hash_a = hash_combine(hash_a, hash_b))), ...);", Style);
- verifyFormat("return (0);", "return (((0)));", Style);
- verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style);
- verifyFormat("return ((... && std::is_convertible_v<TArgsLocal, TArgs>));",
- "return (((... && std::is_convertible_v<TArgsLocal, TArgs>)));",
- Style);
- verifyFormat("MOCK_METHOD(void, Function, (), override);",
- "MOCK_METHOD(void, Function, (), (override));", Style);
-
- Style.MacrosSkippedByRemoveParentheses.push_back("FOO");
- verifyFormat("FOO((a && b));", Style);
- verifyFormat("FOO((int), func, ((std::map<int, int>)), (override));", Style);
-
- Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
- verifyFormat("#define Return0 return (0);", Style);
- verifyFormat("return 0;", "return (0);", Style);
- verifyFormat("co_return 0;", "co_return ((0));", Style);
- verifyFormat("return 0;", "return (((0)));", Style);
- verifyFormat("return ({ 0; });", "return ((({ 0; })));", Style);
- verifyFormat("return (... && std::is_convertible_v<TArgsLocal, TArgs>);",
- "return (((... && std::is_convertible_v<TArgsLocal, TArgs>)));",
- Style);
- verifyFormat("inline decltype(auto) f() {\n"
- " if (a) {\n"
- " return (a);\n"
- " }\n"
- " return (b);\n"
- "}",
- "inline decltype(auto) f() {\n"
- " if (a) {\n"
- " return ((a));\n"
- " }\n"
- " return ((b));\n"
- "}",
- Style);
- verifyFormat("auto g() {\n"
- " decltype(auto) x = [] {\n"
- " auto y = [] {\n"
- " if (a) {\n"
- " return a;\n"
- " }\n"
- " return b;\n"
- " };\n"
- " if (c) {\n"
- " return (c);\n"
- " }\n"
- " return (d);\n"
- " };\n"
- " if (e) {\n"
- " return e;\n"
- " }\n"
- " return f;\n"
- "}",
- "auto g() {\n"
- " decltype(auto) x = [] {\n"
- " auto y = [] {\n"
- " if (a) {\n"
- " return ((a));\n"
- " }\n"
- " return ((b));\n"
- " };\n"
- " if (c) {\n"
- " return ((c));\n"
- " }\n"
- " return ((d));\n"
- " };\n"
- " if (e) {\n"
- " return ((e));\n"
- " }\n"
- " return ((f));\n"
- "}",
- Style);
-
- Style.ColumnLimit = 25;
- verifyFormat("return (a + b) - (c + d);",
- "return (((a + b)) -\n"
- " ((c + d)));",
- Style);
-}
-
-TEST_F(FormatTest, AllowBreakBeforeNoexceptSpecifier) {
- auto Style = getLLVMStyleWithColumns(35);
-
- EXPECT_EQ(Style.AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
- verifyFormat("void foo(int arg1,\n"
- " double arg2) noexcept;",
- Style);
-
- // The following line does not fit within the 35 column limit, but that's what
- // happens with no break allowed.
- verifyFormat("void bar(int arg1, double arg2) noexcept(\n"
- " noexcept(baz(arg1)) &&\n"
- " noexcept(baz(arg2)));",
- Style);
-
- verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments() noexcept;",
- Style);
-
- Style.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Always;
- verifyFormat("void foo(int arg1,\n"
- " double arg2) noexcept;",
- Style);
-
- verifyFormat("void bar(int arg1, double arg2)\n"
- " noexcept(noexcept(baz(arg1)) &&\n"
- " noexcept(baz(arg2)));",
- Style);
-
- verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments()\n"
- " noexcept;",
- Style);
-
- Style.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_OnlyWithParen;
- verifyFormat("void foo(int arg1,\n"
- " double arg2) noexcept;",
- Style);
-
- verifyFormat("void bar(int arg1, double arg2)\n"
- " noexcept(noexcept(baz(arg1)) &&\n"
- " noexcept(baz(arg2)));",
- Style);
-
- verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments() noexcept;",
- Style);
-}
-
-TEST_F(FormatTest, PPBranchesInBracedInit) {
- verifyFormat("A a_{kFlag1,\n"
- "#if BUILD_FLAG\n"
- " kFlag2,\n"
- "#else\n"
- " kFlag3,\n"
- "#endif\n"
- " kFlag4};",
- "A a_{\n"
- " kFlag1,\n"
- "#if BUILD_FLAG\n"
- " kFlag2,\n"
- "#else\n"
- " kFlag3,\n"
- "#endif\n"
- " kFlag4\n"
- "};");
-}
-
-TEST_F(FormatTest, PPDirectivesAndCommentsInBracedInit) {
- verifyFormat("{\n"
- " char *a[] = {\n"
- " /* abc */ \"abc\",\n"
- "#if FOO\n"
- " /* xyz */ \"xyz\",\n"
- "#endif\n"
- " /* last */ \"last\"};\n"
- "}",
- getLLVMStyleWithColumns(30));
-}
-
-TEST_F(FormatTest, BreakAdjacentStringLiterals) {
- constexpr StringRef Code(
- "return \"Code\" \"\\0\\52\\26\\55\\55\\0\" \"x013\" \"\\02\\xBA\";");
-
- verifyFormat("return \"Code\"\n"
- " \"\\0\\52\\26\\55\\55\\0\"\n"
- " \"x013\"\n"
- " \"\\02\\xBA\";",
- Code);
-
- auto Style = getLLVMStyle();
- Style.BreakAdjacentStringLiterals = false;
- verifyFormat(Code, Style);
-}
-
-TEST_F(FormatTest, AlignUTFCommentsAndStringLiterals) {
- verifyFormat(
- "int rus; // А теперь комментарии, например, на русском, 2-байта\n"
- "int long_rus; // Верхний коммент еще не превысил границу в 80, однако\n"
- " // уже отодвинут. Перенос, при этом, отрабатывает верно");
-
- auto Style = getLLVMStyle();
- Style.ColumnLimit = 15;
- verifyNoChange("#define test \\\n"
- " /* 测试 */ \\\n"
- " \"aa\" \\\n"
- " \"bb\"",
- Style);
-
- Style.ColumnLimit = 25;
- verifyFormat("struct foo {\n"
- " int iiiiii; ///< iiiiii\n"
- " int b; ///< ыыы\n"
- " int c; ///< ыыыы\n"
- "};",
- Style);
-
- Style.ColumnLimit = 35;
- verifyFormat("#define SENSOR_DESC_1 \\\n"
- " \"{\" \\\n"
- " \"unit_of_measurement: \\\"°C\\\",\" \\\n"
- " \"}\"",
- Style);
-
- Style.ColumnLimit = 80;
- Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
- verifyFormat("Languages languages = {\n"
- " Language{{'e', 'n'}, U\"Test English\" },\n"
- " Language{{'l', 'v'}, U\"Test Latviešu\"},\n"
- " Language{{'r', 'u'}, U\"Test Русский\" },\n"
- "};",
- Style);
-}
-
-TEST_F(FormatTest, SpaceBetweenKeywordAndLiteral) {
- verifyFormat("return .5;");
- verifyFormat("return not '5';");
- verifyFormat("return sizeof \"5\";");
-}
-
-TEST_F(FormatTest, BreakBinaryOperations) {
- auto Style = getLLVMStyleWithColumns(60);
- FormatStyle::BreakBinaryOperationsOptions ExpectedDefault = {
- FormatStyle::BBO_Never, {}};
- EXPECT_EQ(Style.BreakBinaryOperations, ExpectedDefault);
-
- // Logical operations
- verifyFormat("if (condition1 && condition2) {\n"
- "}",
- Style);
-
- verifyFormat("if (condition1 && condition2 &&\n"
- " (condition3 || condition4) && condition5 &&\n"
- " condition6) {\n"
- "}",
- Style);
-
- verifyFormat("if (loooooooooooooooooooooongcondition1 &&\n"
- " loooooooooooooooooooooongcondition2) {\n"
- "}",
- Style);
-
- // Arithmetic
- verifyFormat("const int result = lhs + rhs;", Style);
-
- verifyFormat("const int result = loooooooongop1 + looooooooongop2 +\n"
- " loooooooooooooooooooooongop3;",
- Style);
-
- verifyFormat("result = longOperand1 + longOperand2 -\n"
- " (longOperand3 + longOperand4) -\n"
- " longOperand5 * longOperand6;",
- Style);
-
- verifyFormat("const int result =\n"
- " operand1 + operand2 - (operand3 + operand4);",
- Style);
-
- // Check operator>> special case.
- verifyFormat("std::cin >> longOperand_1 >> longOperand_2 >>\n"
- " longOperand_3_;",
- Style);
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_OnePerLine;
-
- // Logical operations
- verifyFormat("if (condition1 && condition2) {\n"
- "}",
- Style);
-
- verifyFormat("if (condition1 && // comment\n"
- " condition2 &&\n"
- " (condition3 || condition4) && // comment\n"
- " condition5 &&\n"
- " condition6) {\n"
- "}",
- Style);
-
- verifyFormat("if (loooooooooooooooooooooongcondition1 &&\n"
- " loooooooooooooooooooooongcondition2) {\n"
- "}",
- Style);
-
- // Arithmetic
- verifyFormat("const int result = lhs + rhs;", Style);
-
- verifyFormat("result = loooooooooooooooooooooongop1 +\n"
- " loooooooooooooooooooooongop2 +\n"
- " loooooooooooooooooooooongop3;",
- Style);
-
- verifyFormat("const int result =\n"
- " operand1 + operand2 - (operand3 + operand4);",
- Style);
-
- verifyFormat("result = longOperand1 +\n"
- " longOperand2 -\n"
- " (longOperand3 + longOperand4) -\n"
- " longOperand5 +\n"
- " longOperand6;",
- Style);
-
- verifyFormat("result = operand1 +\n"
- " operand2 -\n"
- " operand3 +\n"
- " operand4 -\n"
- " operand5 +\n"
- " operand6;",
- Style);
-
- // Ensure mixed precedence operations are handled properly
- verifyFormat("result = op1 + op2 * op3 - op4;", Style);
-
- verifyFormat("result = operand1 +\n"
- " operand2 /\n"
- " operand3 +\n"
- " operand4 /\n"
- " operand5 *\n"
- " operand6;",
- Style);
-
- verifyFormat("result = operand1 *\n"
- " operand2 -\n"
- " operand3 *\n"
- " operand4 -\n"
- " operand5 +\n"
- " operand6;",
- Style);
-
- verifyFormat("result = operand1 *\n"
- " (operand2 - operand3 * operand4) -\n"
- " operand5 +\n"
- " operand6;",
- Style);
-
- verifyFormat("result = operand1.member *\n"
- " (operand2.member() - operand3->mem * operand4) -\n"
- " operand5.member() +\n"
- " operand6->member;",
- Style);
-
- // Check operator>> special case.
- verifyFormat("std::cin >>\n"
- " longOperand_1 >>\n"
- " longOperand_2 >>\n"
- " longOperand_3_;",
- Style);
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_RespectPrecedence;
- verifyFormat("result = op1 + op2 * op3 - op4;", Style);
-
- verifyFormat("result = operand1 +\n"
- " operand2 / operand3 +\n"
- " operand4 / operand5 * operand6;",
- Style);
-
- verifyFormat("result = operand1 * operand2 -\n"
- " operand3 * operand4 -\n"
- " operand5 +\n"
- " operand6;",
- Style);
-
- verifyFormat("result = operand1 * (operand2 - operand3 * operand4) -\n"
- " operand5 +\n"
- " operand6;",
- Style);
-
- verifyFormat("std::uint32_t a = byte_buffer[0] |\n"
- " byte_buffer[1] << 8 |\n"
- " byte_buffer[2] << 16 |\n"
- " byte_buffer[3] << 24;",
- Style);
-
- // Check operator>> special case.
- verifyFormat("std::cin >>\n"
- " longOperand_1 >>\n"
- " longOperand_2 >>\n"
- " longOperand_3_;",
- Style);
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_OnePerLine;
- Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
-
- // Logical operations
- verifyFormat("if (condition1 && condition2) {\n"
- "}",
- Style);
-
- verifyFormat("if (loooooooooooooooooooooongcondition1\n"
- " && loooooooooooooooooooooongcondition2) {\n"
- "}",
- Style);
-
- // Arithmetic
- verifyFormat("const int result = lhs + rhs;", Style);
-
- verifyFormat("result = loooooooooooooooooooooongop1\n"
- " + loooooooooooooooooooooongop2\n"
- " + loooooooooooooooooooooongop3;",
- Style);
-
- verifyFormat("const int result =\n"
- " operand1 + operand2 - (operand3 + operand4);",
- Style);
-
- verifyFormat("result = longOperand1\n"
- " + longOperand2\n"
- " - (longOperand3 + longOperand4)\n"
- " - longOperand5\n"
- " + longOperand6;",
- Style);
-
- verifyFormat("result = operand1\n"
- " + operand2\n"
- " - operand3\n"
- " + operand4\n"
- " - operand5\n"
- " + operand6;",
- Style);
-
- // Ensure mixed precedence operations are handled properly
- verifyFormat("result = op1 + op2 * op3 - op4;", Style);
-
- verifyFormat("result = operand1\n"
- " + operand2\n"
- " / operand3\n"
- " + operand4\n"
- " / operand5\n"
- " * operand6;",
- Style);
-
- verifyFormat("result = operand1\n"
- " * operand2\n"
- " - operand3\n"
- " * operand4\n"
- " - operand5\n"
- " + operand6;",
- Style);
-
- verifyFormat("result = operand1\n"
- " * (operand2 - operand3 * operand4)\n"
- " - operand5\n"
- " + operand6;",
- Style);
-
- verifyFormat("std::uint32_t a = byte_buffer[0]\n"
- " | byte_buffer[1]\n"
- " << 8\n"
- " | byte_buffer[2]\n"
- " << 16\n"
- " | byte_buffer[3]\n"
- " << 24;",
- Style);
-
- // Check operator>> special case.
- verifyFormat("std::cin\n"
- " >> longOperand_1\n"
- " >> longOperand_2\n"
- " >> longOperand_3_;",
- Style);
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_RespectPrecedence;
- verifyFormat("result = op1 + op2 * op3 - op4;", Style);
-
- verifyFormat("result = operand1\n"
- " + operand2 / operand3\n"
- " + operand4 / operand5 * operand6;",
- Style);
-
- verifyFormat("result = operand1 * operand2\n"
- " - operand3 * operand4\n"
- " - operand5\n"
- " + operand6;",
- Style);
-
- verifyFormat("result = operand1 * (operand2 - operand3 * operand4)\n"
- " - operand5\n"
- " + operand6;",
- Style);
-
- verifyFormat("std::uint32_t a = byte_buffer[0]\n"
- " | byte_buffer[1] << 8\n"
- " | byte_buffer[2] << 16\n"
- " | byte_buffer[3] << 24;",
- Style);
-
- // Check operator>> special case.
- verifyFormat("std::cin\n"
- " >> longOperand_1\n"
- " >> longOperand_2\n"
- " >> longOperand_3_;",
- Style);
-}
-
-TEST_F(FormatTest, BreakBinaryOperationsPerOperator) {
- auto Style = getLLVMStyleWithColumns(60);
-
- // Per-operator override: && and || are OnePerLine, rest is Never (default).
- FormatStyle::BinaryOperationBreakRule LogicalRule;
- LogicalRule.Operators = {tok::ampamp, tok::pipepipe};
- LogicalRule.Style = FormatStyle::BBO_OnePerLine;
- LogicalRule.MinChainLength = 0;
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_Never;
- Style.BreakBinaryOperations.PerOperator = {LogicalRule};
-
- // Logical operators break one-per-line when line is too long.
- verifyFormat("bool valid = isConnectionReady() &&\n"
- " isSessionNotExpired() &&\n"
- " hasRequiredPermission();",
- Style);
-
- // Arithmetic operators stay with default (Never).
- verifyFormat("int total = unitBasePrice + shippingCostPerItem +\n"
- " applicableTaxAmount + handlingFeePerUnit;",
- Style);
-
- // Short logical chain that fits stays on one line.
- verifyFormat("bool x = a && b && c;", Style);
-
- // Multiple PerOperator groups: && and || plus | operators.
- FormatStyle::BinaryOperationBreakRule BitwiseOrRule;
- BitwiseOrRule.Operators = {tok::pipe};
- BitwiseOrRule.Style = FormatStyle::BBO_OnePerLine;
- BitwiseOrRule.MinChainLength = 0;
-
- Style.BreakBinaryOperations.PerOperator = {LogicalRule, BitwiseOrRule};
-
- // | operators should break one-per-line.
- verifyFormat("int flags = OPTION_VERBOSE_OUTPUT |\n"
- " OPTION_RECURSIVE_SCAN |\n"
- " OPTION_FORCE_OVERWRITE;",
- Style);
-
- // && still works in multi-group configuration.
- verifyFormat("bool valid = isConnectionReady() &&\n"
- " isSessionNotExpired() &&\n"
- " hasRequiredPermission();",
- Style);
-
- // + stays with default (Never) even with multi-group.
- verifyFormat("int total = unitBasePrice + shippingCostPerItem +\n"
- " applicableTaxAmount + handlingFeePerUnit;",
- Style);
-
- // | OnePerLine with << sub-expressions: << stays grouped.
- Style.BreakBinaryOperations.PerOperator = {BitwiseOrRule};
- verifyFormat("std::uint32_t a = byte_buffer[0] |\n"
- " byte_buffer[1] << 8 |\n"
- " byte_buffer[2] << 16 |\n"
- " byte_buffer[3] << 24;",
- Style);
-
- // >> (stream extraction) OnePerLine: clang-format splits >> into two >
- // tokens, but per-operator rules for >> must still work.
- FormatStyle::BinaryOperationBreakRule ShiftRightRule;
- ShiftRightRule.Operators = {tok::greatergreater};
- ShiftRightRule.Style = FormatStyle::BBO_OnePerLine;
- ShiftRightRule.MinChainLength = 0;
-
- Style.BreakBinaryOperations.PerOperator = {ShiftRightRule};
- verifyFormat("in >>\n"
- " packet_id >>\n"
- " packet_version >>\n"
- " packet_number >>\n"
- " packet_scale;",
- Style);
-}
-
-TEST_F(FormatTest, BreakBinaryOperationsMinChainLength) {
- auto Style = getLLVMStyleWithColumns(60);
-
- // MinChainLength = 3: chains shorter than 3 don't force breaks.
- FormatStyle::BinaryOperationBreakRule LogicalRule;
- LogicalRule.Operators = {tok::ampamp, tok::pipepipe};
- LogicalRule.Style = FormatStyle::BBO_OnePerLine;
- LogicalRule.MinChainLength = 3;
-
- Style.BreakBinaryOperations.Default = FormatStyle::BBO_Never;
- Style.BreakBinaryOperations.PerOperator = {LogicalRule};
-
- // Chain of 2 — below MinChainLength, no forced one-per-line.
- verifyFormat("bool ok =\n"
- " isConnectionReady(cfg) && isSessionNotExpired(cfg);",
- Style);
-
- // Chain of 3 — meets MinChainLength, one-per-line.
- verifyFormat("bool ok = isConnectionReady(cfg) &&\n"
- " isSessionNotExpired(cfg) &&\n"
- " hasRequiredPermission(cfg);",
- Style);
-
- // Chain of 4 — above MinChainLength, one-per-line.
- verifyFormat("bool ok = isConnectionReady(cfg) &&\n"
- " isSessionNotExpired(cfg) &&\n"
- " hasRequiredPermission(cfg) &&\n"
- " isFeatureEnabled(cfg);",
- Style);
-}
-
-TEST_F(FormatTest, RemoveEmptyLinesInUnwrappedLines) {
- auto Style = getLLVMStyle();
- Style.RemoveEmptyLinesInUnwrappedLines = true;
-
- verifyFormat("int c = a + b;",
- "int c\n"
- "\n"
- " = a + b;",
- Style);
-
- verifyFormat("enum : unsigned { AA = 0, BB } myEnum;",
- "enum : unsigned\n"
- "\n"
- "{\n"
- " AA = 0,\n"
- " BB\n"
- "} myEnum;",
- Style);
-
- verifyFormat("class B : public E {\n"
- "private:\n"
- "};",
- "class B : public E\n"
- "\n"
- "{\n"
- "private:\n"
- "};",
- Style);
-
- verifyFormat(
- "struct AAAAAAAAAAAAAAA test[3] = {{56, 23, \"hello\"}, {7, 5, \"!!\"}};",
- "struct AAAAAAAAAAAAAAA test[3] = {{56,\n"
- "\n"
- " 23, \"hello\"},\n"
- " {7, 5, \"!!\"}};",
- Style);
-
- verifyFormat("int myFunction(int aaaaaaaaaaaaa, int ccccccccccccc, int d);",
- "int myFunction(\n"
- "\n"
- " int aaaaaaaaaaaaa,\n"
- "\n"
- " int ccccccccccccc, int d);",
- Style);
-
- verifyFormat("switch (e) {\n"
- "case 1:\n"
- " return e;\n"
- "case 2:\n"
- " return 2;\n"
- "}",
- "switch (\n"
- "\n"
- " e) {\n"
- "case 1:\n"
- " return e;\n"
- "case 2:\n"
- " return 2;\n"
- "}",
- Style);
-
- verifyFormat("while (true) {\n"
- "}",
- "while (\n"
- "\n"
- " true) {\n"
- "}",
- Style);
-
- verifyFormat("void loooonFunctionIsVeryLongButNotAsLongAsJavaTypeNames(\n"
- " std::map<int, std::string> *outputMap);",
- "void loooonFunctionIsVeryLongButNotAsLongAsJavaTypeNames\n"
- "\n"
- " (std::map<int, std::string> *outputMap);",
- Style);
-}
-
-TEST_F(FormatTest, KeepFormFeed) {
- auto Style = getLLVMStyle();
- Style.KeepFormFeed = true;
-
- constexpr StringRef NoFormFeed("int i;\n"
- "\n"
- "void f();");
- verifyFormat(NoFormFeed,
- "int i;\n"
- " \f\n"
- "void f();",
- Style);
- verifyFormat(NoFormFeed,
- "int i;\n"
- "\n"
- "\fvoid f();",
- Style);
- verifyFormat(NoFormFeed,
- "\fint i;\n"
- "\n"
- "void f();",
- Style);
- verifyFormat(NoFormFeed,
- "int i;\n"
- "\n"
- "void f();\f",
- Style);
-
- constexpr StringRef FormFeed("int i;\n"
- "\f\n"
- "void f();");
- verifyNoChange(FormFeed, Style);
-
- Style.LineEnding = FormatStyle::LE_LF;
- verifyFormat(FormFeed,
- "int i;\r\n"
- "\f\r\n"
- "void f();",
- Style);
-
- constexpr StringRef FormFeedBeforeEmptyLine("int i;\n"
- "\f\n"
- "\n"
- "void f();");
- Style.MaxEmptyLinesToKeep = 2;
- verifyFormat(FormFeedBeforeEmptyLine,
- "int i;\n"
- "\n"
- "\f\n"
- "void f();",
- Style);
- verifyFormat(FormFeedBeforeEmptyLine,
- "int i;\n"
- "\f\n"
- "\f\n"
- "void f();",
- Style);
-}
-
-TEST_F(FormatTest, ShortNamespacesOption) {
- auto Style = getLLVMStyleWithColumns(60);
- Style.AllowShortNamespacesOnASingleLine = true;
-
- verifyFormat("namespace {\n"
- "void xxxxx(nnn::TTTTT *mmm, YYYYY &yyyyy);\n"
- "} // namespace",
- Style);
-
- Style.ColumnLimit = 80;
- Style.CompactNamespaces = true;
- Style.FixNamespaceComments = false;
-
- // Basic functionality.
- verifyFormat("namespace foo { class bar; }", Style);
- verifyFormat("namespace foo::bar { class baz; }", Style);
- verifyFormat("namespace { class bar; }", Style);
- verifyFormat("namespace foo {\n"
- "class bar;\n"
- "class baz;\n"
- "}",
- Style);
-
- // Trailing comments prevent merging.
- verifyFormat("namespace foo { namespace baz {\n"
- "class qux;\n"
- "} // comment\n"
- "}",
- Style);
-
- // Make sure code doesn't walk too far on unbalanced code.
- verifyFormat("namespace foo {", Style);
- verifyFormat("namespace foo {\n"
- "class baz;",
- Style);
- verifyFormat("namespace foo {\n"
- "namespace bar { class baz; }",
- Style);
-
- // Nested namespaces.
- verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
-
- // Without CompactNamespaces, we won't merge consecutive namespace
- // declarations.
- Style.CompactNamespaces = false;
- verifyFormat("namespace foo {\n"
- "namespace bar { class baz; }\n"
- "}",
- Style);
-
- verifyFormat("namespace foo {\n"
- "namespace bar { class baz; }\n"
- "namespace qux { class quux; }\n"
- "}",
- Style);
-
- Style.CompactNamespaces = true;
-
- // Varying inner content.
- verifyFormat("namespace foo {\n"
- "int f() { return 5; }\n"
- "}",
- Style);
- verifyFormat("namespace foo { template <T> struct bar; }", Style);
- verifyFormat("namespace foo { constexpr int num = 42; }", Style);
-
- // Validate nested namespace wrapping scenarios around the ColumnLimit.
- Style.ColumnLimit = 64;
-
- // Validate just under the ColumnLimit.
- verifyFormat(
- "namespace foo { namespace bar { namespace baz { class qux; } } }",
- Style);
-
- // Validate just over the ColumnLimit.
- verifyFormat("namespace foo { namespace baar { namespace baaz {\n"
- "class quux;\n"
- "}}}",
- Style);
-
- verifyFormat(
- "namespace foo { namespace bar { namespace baz { namespace qux {\n"
- "class quux;\n"
- "}}}}",
- Style);
-
- // Validate that the ColumnLimit logic accounts for trailing content as well.
- verifyFormat("namespace foo { namespace bar { class qux; } } // extra",
- Style);
-
- verifyFormat("namespace foo { namespace bar { namespace baz {\n"
- "class qux;\n"
- "}}} // extra",
- Style);
-
- // FIXME: Ideally AllowShortNamespacesOnASingleLine would disable the trailing
- // namespace comment from 'FixNamespaceComments', as it's not really necessary
- // in this scenario, but the two options work at very different layers of the
- // formatter, so I'm not sure how to make them interact.
- //
- // As it stands, the trailing comment will be added and likely make the line
- // too long to fit within the ColumnLimit, reducing the how likely the line
- // will still fit on a single line. The recommendation for now is to use the
- // concatenated namespace syntax instead. e.g. 'namespace foo::bar'
- Style.FixNamespaceComments = true;
- verifyFormat(
- "namespace foo { namespace bar { namespace baz {\n"
- "class qux;\n"
- "}}} // namespace foo::bar::baz",
- "namespace foo { namespace bar { namespace baz { class qux; } } }",
- Style);
- Style.FixNamespaceComments = false;
-
- Style.BreakBeforeBraces = FormatStyle::BS_Custom;
- Style.BraceWrapping.AfterNamespace = true;
- verifyFormat("namespace foo { class bar; }", Style);
- verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
- verifyFormat("namespace foo\n"
- "{ // comment\n"
- "class bar;\n"
- "}",
- Style);
- verifyFormat("namespace foo { class bar; }",
- "namespace foo {\n"
- "class bar;\n"
- "}",
- Style);
- verifyFormat("namespace foo\n"
- "{\n"
- "namespace bar\n"
- "{ // comment\n"
- "class baz;\n"
- "}\n"
- "}",
- Style);
- verifyFormat("namespace foo // comment\n"
- "{\n"
- "class baz;\n"
- "}",
- Style);
-}
-
-TEST_F(FormatTest, WrapNamespaceBodyWithEmptyLinesNever) {
- auto Style = getLLVMStyle();
- Style.FixNamespaceComments = false;
- Style.MaxEmptyLinesToKeep = 2;
- Style.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Never;
-
- // Empty namespace.
- verifyFormat("namespace N {}", Style);
-
- // Single namespace.
- verifyFormat("namespace N {\n"
- "int f1(int a) { return 2 * a; }\n"
- "}",
- "namespace N {\n"
- "\n"
- "\n"
- "int f1(int a) { return 2 * a; }\n"
- "\n"
- "\n"
- "}",
- Style);
-
- // Nested namespace.
- verifyFormat("namespace N1 {\n"
- "namespace N2 {\n"
- "int a = 1;\n"
- "}\n"
- "}",
- "namespace N1 {\n"
- "\n"
- "\n"
- "namespace N2 {\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "}\n"
- "\n"
- "\n"
- "}",
- Style);
-
- Style.CompactNamespaces = true;
-
- verifyFormat("namespace N1 { namespace N2 {\n"
- "int a = 1;\n"
- "}}",
- "namespace N1 { namespace N2 {\n"
- "\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "\n"
- "}}",
- Style);
-}
-
-TEST_F(FormatTest, WrapNamespaceBodyWithEmptyLinesAlways) {
- auto Style = getLLVMStyle();
- Style.FixNamespaceComments = false;
- Style.MaxEmptyLinesToKeep = 2;
- Style.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Always;
-
- // Empty namespace.
- verifyFormat("namespace N {}", Style);
-
- // Single namespace.
- verifyFormat("namespace N {\n"
- "\n"
- "int f1(int a) { return 2 * a; }\n"
- "\n"
- "}",
- "namespace N {\n"
- "int f1(int a) { return 2 * a; }\n"
- "}",
- Style);
-
- // Nested namespace.
- verifyFormat("namespace N1 {\n"
- "namespace N2 {\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "}\n"
- "}",
- "namespace N1 {\n"
- "namespace N2 {\n"
- "int a = 1;\n"
- "}\n"
- "}",
- Style);
-
- verifyFormat("namespace N1 {\n"
- "\n"
- "namespace N2 {\n"
- "\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "\n"
- "}\n"
- "\n"
- "}",
- "namespace N1 {\n"
- "\n"
- "namespace N2 {\n"
- "\n"
- "\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "\n"
- "\n"
- "}\n"
- "\n"
- "}",
- Style);
-
- Style.CompactNamespaces = true;
-
- verifyFormat("namespace N1 { namespace N2 {\n"
- "\n"
- "int a = 1;\n"
- "\n"
- "}}",
- "namespace N1 { namespace N2 {\n"
- "int a = 1;\n"
- "}}",
- Style);
-}
-
-TEST_F(FormatTest, BreakBeforeClassName) {
- verifyFormat("class ABSL_ATTRIBUTE_TRIVIAL_ABI ABSL_NULLABILITY_COMPATIBLE\n"
- " ArenaSafeUniquePtr {};");
-}
-
-TEST_F(FormatTest, KeywordedFunctionLikeMacros) {
- constexpr StringRef Code("Q_PROPERTY(int name\n"
- " READ name\n"
- " WRITE setName\n"
- " NOTIFY nameChanged)");
- constexpr StringRef Code2("class A {\n"
- " Q_PROPERTY(int name\n"
- " READ name\n"
- " WRITE setName\n"
- " NOTIFY nameChanged)\n"
- "};");
-
- auto Style = getLLVMStyle();
- Style.AllowBreakBeforeQtProperty = true;
-
- Style.BinPackParameters = FormatStyle::BPPS_AlwaysOnePerLine;
- verifyFormat(Code, Style);
- verifyFormat(Code2, Style);
-
- Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
- Style.ColumnLimit = 40;
- verifyFormat(Code, Style);
- verifyFormat(Code2, Style);
- verifyFormat("/* sdf */ Q_PROPERTY(int name\n"
- " READ name\n"
- " WRITE setName\n"
- " NOTIFY nameChanged)",
- Style);
-}
-
-TEST_F(FormatTest, UnbalancedAngleBrackets) {
- verifyFormat("template <");
-
- verifyNoCrash("typename foo<bar>::value, const String &>::type f();",
- getLLVMStyleWithColumns(50));
-
- verifyNoCrash(
- ">\n"
- " f({\n"
- " {}inner> () __attribute __attribute__((foo())) int foo(void)\n"
- " {};\n"
- " }, );",
- getLLVMStyleWithColumns(70));
-}
-
-TEST_F(FormatTest, LambdaArrowAsTrailingReturnArrow) {
- verifyNoCrash("void foo()([] consteval -> int {}())");
-}
-
-} // namespace
-} // namespace test
-} // namespace format
-} // namespace clang
+//===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FormatTestBase.h"
+
+#define DEBUG_TYPE "format-test"
+
+namespace clang {
+namespace format {
+namespace test {
+namespace {
+
+class FormatTest : public test::FormatTestBase {};
+
+TEST_F(FormatTest, MessUp) {
+ EXPECT_EQ("1 2 3", messUp("1 2 3"));
+ EXPECT_EQ("1 2 3", messUp("1\n2\n3"));
+ EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
+ EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
+ EXPECT_EQ("a\n#b c d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
+}
+
+TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
+ EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
+}
+
+TEST_F(FormatTest, LLVMStyleOverride) {
+ EXPECT_EQ(FormatStyle::LK_Proto,
+ getLLVMStyle(FormatStyle::LK_Proto).Language);
+}
+
+//===----------------------------------------------------------------------===//
+// Basic function tests.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { verifyFormat(";"); }
+
+TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
+ verifyFormat("int i;", " int i;");
+ verifyFormat("\nint i;", " \n\t \v \f int i;");
+ verifyFormat("int i;\nint j;", " int i; int j;");
+ verifyFormat("int i;\nint j;", " int i;\n int j;");
+
+ auto Style = getLLVMStyle();
+ Style.KeepEmptyLines.AtStartOfFile = false;
+ verifyFormat("int i;", " \n\t \v \f int i;", Style);
+}
+
+TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
+ verifyFormat("int i;", "int\ni;");
+}
+
+TEST_F(FormatTest, FormatsNestedBlockStatements) {
+ verifyFormat("{\n"
+ " {\n"
+ " {\n"
+ " }\n"
+ " }\n"
+ "}",
+ "{{{}}}");
+}
+
+TEST_F(FormatTest, FormatsNestedCall) {
+ verifyFormat("Method(f1, f2(f3));");
+ verifyFormat("Method(f1(f2, f3()));");
+ verifyFormat("Method(f1(f2, (f3())));");
+}
+
+TEST_F(FormatTest, NestedNameSpecifiers) {
+ verifyFormat("vector<::Type> v;");
+ verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
+ verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
+ verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
+ verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
+ verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
+ verifyFormat("bool a = 2 < ::SomeFunction();");
+ verifyFormat("ALWAYS_INLINE ::std::string getName();");
+ verifyFormat("some::string getName();");
+}
+
+TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
+ verifyFormat("if (a) {\n"
+ " f();\n"
+ "}",
+ "if(a){f();}");
+ EXPECT_EQ(4, ReplacementCount);
+ verifyNoChange("if (a) {\n"
+ " f();\n"
+ "}");
+ EXPECT_EQ(0, ReplacementCount);
+ verifyNoChange("/*\r\n"
+ "\r\n"
+ "*/");
+ EXPECT_EQ(0, ReplacementCount);
+}
+
+TEST_F(FormatTest, RemovesEmptyLines) {
+ verifyFormat("class C {\n"
+ " int i;\n"
+ "};",
+ "class C {\n"
+ " int i;\n"
+ "\n"
+ "};");
+
+ // Don't remove empty lines at the start of namespaces or extern "C" blocks.
+ verifyFormat("namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+ verifyFormat("/* something */ namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "/* something */ namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+ verifyFormat("inline namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "inline namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+ verifyFormat("/* something */ inline namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "/* something */ inline namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+ verifyFormat("export namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "export namespace N {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+ verifyFormat("extern /**/ \"C\" /**/ {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "extern /**/ \"C\" /**/ {\n"
+ "\n"
+ "int i;\n"
+ "}",
+ getGoogleStyle());
+
+ auto CustomStyle = getLLVMStyle();
+ CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
+ CustomStyle.BraceWrapping.AfterNamespace = true;
+ CustomStyle.KeepEmptyLines.AtStartOfBlock = false;
+ verifyFormat("namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "namespace N\n"
+ "{\n"
+ "\n"
+ "\n"
+ "int i;\n"
+ "}",
+ CustomStyle);
+ verifyFormat("/* something */ namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "/* something */ namespace N {\n"
+ "\n"
+ "\n"
+ "int i;\n"
+ "}",
+ CustomStyle);
+ verifyFormat("inline namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "inline namespace N\n"
+ "{\n"
+ "\n"
+ "\n"
+ "int i;\n"
+ "}",
+ CustomStyle);
+ verifyFormat("/* something */ inline namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "/* something */ inline namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ CustomStyle);
+ verifyFormat("export namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ "export namespace N\n"
+ "{\n"
+ "\n"
+ "int i;\n"
+ "}",
+ CustomStyle);
+ verifyFormat("namespace a\n"
+ "{\n"
+ "namespace b\n"
+ "{\n"
+ "\n"
+ "class AA {};\n"
+ "\n"
+ "} // namespace b\n"
+ "} // namespace a",
+ "namespace a\n"
+ "{\n"
+ "namespace b\n"
+ "{\n"
+ "\n"
+ "\n"
+ "class AA {};\n"
+ "\n"
+ "\n"
+ "}\n"
+ "}",
+ CustomStyle);
+ verifyFormat("namespace A /* comment */\n"
+ "{\n"
+ "class B {}\n"
+ "} // namespace A",
+ "namespace A /* comment */ { class B {} }", CustomStyle);
+ verifyFormat("namespace A\n"
+ "{ /* comment */\n"
+ "class B {}\n"
+ "} // namespace A",
+ "namespace A {/* comment */ class B {} }", CustomStyle);
+ verifyFormat("namespace A\n"
+ "{ /* comment */\n"
+ "\n"
+ "class B {}\n"
+ "\n"
+ ""
+ "} // namespace A",
+ "namespace A { /* comment */\n"
+ "\n"
+ "\n"
+ "class B {}\n"
+ "\n"
+ "\n"
+ "}",
+ CustomStyle);
+ verifyFormat("namespace A /* comment */\n"
+ "{\n"
+ "\n"
+ "class B {}\n"
+ "\n"
+ "} // namespace A",
+ "namespace A/* comment */ {\n"
+ "\n"
+ "\n"
+ "class B {}\n"
+ "\n"
+ "\n"
+ "}",
+ CustomStyle);
+
+ // ...but do keep inlining and removing empty lines for non-block extern "C"
+ // functions.
+ verifyGoogleFormat("extern \"C\" int f() { return 42; }");
+ verifyFormat("extern \"C\" int f() {\n"
+ " int i = 42;\n"
+ " return i;\n"
+ "}",
+ "extern \"C\" int f() {\n"
+ "\n"
+ " int i = 42;\n"
+ " return i;\n"
+ "}",
+ getGoogleStyle());
+
+ // Remove empty lines at the beginning and end of blocks.
+ verifyFormat("void f() {\n"
+ "\n"
+ " if (a) {\n"
+ "\n"
+ " f();\n"
+ " }\n"
+ "}",
+ "void f() {\n"
+ "\n"
+ " if (a) {\n"
+ "\n"
+ " f();\n"
+ "\n"
+ " }\n"
+ "\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " if (a) {\n"
+ " f();\n"
+ " }\n"
+ "}",
+ "void f() {\n"
+ "\n"
+ " if (a) {\n"
+ "\n"
+ " f();\n"
+ "\n"
+ " }\n"
+ "\n"
+ "}",
+ getGoogleStyle());
+
+ // Don't remove empty lines in more complex control statements.
+ verifyFormat("void f() {\n"
+ " if (a) {\n"
+ " f();\n"
+ "\n"
+ " } else if (b) {\n"
+ " f();\n"
+ " }\n"
+ "}",
+ "void f() {\n"
+ " if (a) {\n"
+ " f();\n"
+ "\n"
+ " } else if (b) {\n"
+ " f();\n"
+ "\n"
+ " }\n"
+ "\n"
+ "}");
+
+ // Don't remove empty lines before namespace endings.
+ FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
+ LLVMWithNoNamespaceFix.FixNamespaceComments = false;
+ verifyNoChange("namespace {\n"
+ "int i;\n"
+ "\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace {\n"
+ "int i;\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyNoChange("namespace {\n"
+ "int i;\n"
+ "\n"
+ "};",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace {\n"
+ "int i;\n"
+ "};",
+ LLVMWithNoNamespaceFix);
+ verifyNoChange("namespace {\n"
+ "int i;\n"
+ "\n"
+ "}");
+ verifyFormat("namespace {\n"
+ "int i;\n"
+ "\n"
+ "} // namespace",
+ "namespace {\n"
+ "int i;\n"
+ "\n"
+ "} // namespace");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ Style.MaxEmptyLinesToKeep = 2;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ Style.BraceWrapping.AfterFunction = true;
+ Style.KeepEmptyLines.AtStartOfBlock = false;
+
+ verifyFormat("class Foo\n"
+ "{\n"
+ " Foo() {}\n"
+ "\n"
+ " void funk() {}\n"
+ "};",
+ "class Foo\n"
+ "{\n"
+ " Foo()\n"
+ " {\n"
+ " }\n"
+ "\n"
+ " void funk() {}\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
+ verifyFormat("x = (a) and (b);");
+ verifyFormat("x = (a) or (b);");
+ verifyFormat("x = (a) bitand (b);");
+ verifyFormat("x = (a) bitor (b);");
+ verifyFormat("x = (a) not_eq (b);");
+ verifyFormat("x = (a) and_eq (b);");
+ verifyFormat("x = (a) or_eq (b);");
+ verifyFormat("x = (a) xor (b);");
+}
+
+TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
+ verifyFormat("x = compl(a);");
+ verifyFormat("x = not(a);");
+ verifyFormat("x = bitand(a);");
+ // Unary operator must not be merged with the next identifier
+ verifyFormat("x = compl a;");
+ verifyFormat("x = not a;");
+ verifyFormat("x = bitand a;");
+}
+
+//===----------------------------------------------------------------------===//
+// Tests for control statements.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
+ verifyFormat("if (true)\n f();\ng();");
+ verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();");
+ verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
+ verifyFormat("if constexpr (true)\n"
+ " f();\ng();");
+ verifyFormat("if CONSTEXPR (true)\n"
+ " f();\ng();");
+ verifyFormat("if constexpr (a)\n"
+ " if constexpr (b)\n"
+ " if constexpr (c)\n"
+ " g();\n"
+ "h();");
+ verifyFormat("if CONSTEXPR (a)\n"
+ " if CONSTEXPR (b)\n"
+ " if CONSTEXPR (c)\n"
+ " g();\n"
+ "h();");
+ verifyFormat("if constexpr (a)\n"
+ " if constexpr (b) {\n"
+ " f();\n"
+ " }\n"
+ "g();");
+ verifyFormat("if CONSTEXPR (a)\n"
+ " if CONSTEXPR (b) {\n"
+ " f();\n"
+ " }\n"
+ "g();");
+
+ verifyFormat("if consteval {\n}");
+ verifyFormat("if !consteval {\n}");
+ verifyFormat("if not consteval {\n}");
+ verifyFormat("if consteval {\n} else {\n}");
+ verifyFormat("if !consteval {\n} else {\n}");
+ verifyFormat("if consteval {\n"
+ " f();\n"
+ "}");
+ verifyFormat("if !consteval {\n"
+ " f();\n"
+ "}");
+ verifyFormat("if consteval {\n"
+ " f();\n"
+ "} else {\n"
+ " g();\n"
+ "}");
+ verifyFormat("if CONSTEVAL {\n"
+ " f();\n"
+ "}");
+ verifyFormat("if !CONSTEVAL {\n"
+ " f();\n"
+ "}");
+
+ verifyFormat("if (a)\n"
+ " g();");
+ verifyFormat("if (a) {\n"
+ " g()\n"
+ "};");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else\n"
+ " g();");
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else\n"
+ " g();");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}");
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();");
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}");
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}");
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}");
+
+ FormatStyle AllowsMergedIf = getLLVMStyle();
+ AllowsMergedIf.IfMacros.push_back("MYIF");
+ AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ verifyFormat("if (a)\n"
+ " // comment\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("{\n"
+ " if (a)\n"
+ " label:\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("#define A \\\n"
+ " if (a) \\\n"
+ " label: \\\n"
+ " f()",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " ;",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " if (b) return;",
+ AllowsMergedIf);
+
+ verifyFormat("if (a) // Can't merge this\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("if (a) /* still don't merge */\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("if (a) { // Never merge this\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) { /* Never merge this */\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " // comment\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("{\n"
+ " MYIF (a)\n"
+ " label:\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("#define A \\\n"
+ " MYIF (a) \\\n"
+ " label: \\\n"
+ " f()",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " ;",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " MYIF (b) return;",
+ AllowsMergedIf);
+
+ verifyFormat("MYIF (a) // Can't merge this\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) /* still don't merge */\n"
+ " f();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) { // Never merge this\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) { /* Never merge this */\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+
+ AllowsMergedIf.ColumnLimit = 14;
+ // Where line-lengths matter, a 2-letter synonym that maintains line length.
+ // Not IF to avoid any confusion that IF is somehow special.
+ AllowsMergedIf.IfMacros.push_back("FI");
+ verifyFormat("if (a) return;", AllowsMergedIf);
+ verifyFormat("if (aaaaaaaaa)\n"
+ " return;",
+ AllowsMergedIf);
+ verifyFormat("FI (a) return;", AllowsMergedIf);
+ verifyFormat("FI (aaaaaaaaa)\n"
+ " return;",
+ AllowsMergedIf);
+
+ AllowsMergedIf.ColumnLimit = 13;
+ verifyFormat("if (a)\n return;", AllowsMergedIf);
+ verifyFormat("FI (a)\n return;", AllowsMergedIf);
+
+ FormatStyle AllowsMergedIfElse = getLLVMStyle();
+ AllowsMergedIfElse.IfMacros.push_back("MYIF");
+ AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_AllIfsAndElse;
+ verifyFormat("if (a)\n"
+ " // comment\n"
+ " f();\n"
+ "else\n"
+ " // comment\n"
+ " f();",
+ AllowsMergedIfElse);
+ verifyFormat("{\n"
+ " if (a)\n"
+ " label:\n"
+ " f();\n"
+ " else\n"
+ " label:\n"
+ " f();\n"
+ "}",
+ AllowsMergedIfElse);
+ verifyFormat("if (a)\n"
+ " ;\n"
+ "else\n"
+ " ;",
+ AllowsMergedIfElse);
+ verifyFormat("if (a) {\n"
+ "} else {\n"
+ "}",
+ AllowsMergedIfElse);
+ verifyFormat("if (a) return;\n"
+ "else if (b) return;\n"
+ "else return;",
+ AllowsMergedIfElse);
+ verifyFormat("if (a) {\n"
+ "} else return;",
+ AllowsMergedIfElse);
+ verifyFormat("if (a) {\n"
+ "} else if (b) return;\n"
+ "else return;",
+ AllowsMergedIfElse);
+ verifyFormat("if (a) return;\n"
+ "else if (b) {\n"
+ "} else return;",
+ AllowsMergedIfElse);
+ verifyFormat("if (a)\n"
+ " if (b) return;\n"
+ " else return;",
+ AllowsMergedIfElse);
+ verifyFormat("if constexpr (a)\n"
+ " if constexpr (b) return;\n"
+ " else if constexpr (c) return;\n"
+ " else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a)\n"
+ " // comment\n"
+ " f();\n"
+ "else\n"
+ " // comment\n"
+ " f();",
+ AllowsMergedIfElse);
+ verifyFormat("{\n"
+ " MYIF (a)\n"
+ " label:\n"
+ " f();\n"
+ " else\n"
+ " label:\n"
+ " f();\n"
+ "}",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a)\n"
+ " ;\n"
+ "else\n"
+ " ;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a) {\n"
+ "} else {\n"
+ "}",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a) return;\n"
+ "else MYIF (b) return;\n"
+ "else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a) {\n"
+ "} else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a) {\n"
+ "} else MYIF (b) return;\n"
+ "else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a) return;\n"
+ "else MYIF (b) {\n"
+ "} else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF (a)\n"
+ " MYIF (b) return;\n"
+ " else return;",
+ AllowsMergedIfElse);
+ verifyFormat("MYIF constexpr (a)\n"
+ " MYIF constexpr (b) return;\n"
+ " else MYIF constexpr (c) return;\n"
+ " else return;",
+ AllowsMergedIfElse);
+}
+
+TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
+ FormatStyle AllowsMergedIf = getLLVMStyle();
+ AllowsMergedIf.IfMacros.push_back("MYIF");
+ AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ verifyFormat("if (a)\n"
+ " f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " f();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+
+ verifyFormat("if (a) g();", AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " f();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+
+ verifyFormat("MYIF (a) g();", AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else MYIF (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else MYIF (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a)\n"
+ " g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_OnlyFirstIf;
+
+ verifyFormat("if (a) f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) f();\n"
+ "else {\n"
+ " if (a) f();\n"
+ " else {\n"
+ " g();\n"
+ " }\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ verifyFormat("if (a) g();", AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) f();\n"
+ "else {\n"
+ " if (a) f();\n"
+ " else {\n"
+ " g();\n"
+ " }\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ verifyFormat("MYIF (a) g();", AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b)\n"
+ " g();\n"
+ "else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else\n"
+ " g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_AllIfsAndElse;
+
+ verifyFormat("if (a) f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) f();\n"
+ "else {\n"
+ " if (a) f();\n"
+ " else {\n"
+ " g();\n"
+ " }\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ verifyFormat("if (a) g();", AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else g();",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("if (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) f();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) f();\n"
+ "else {\n"
+ " if (a) f();\n"
+ " else {\n"
+ " g();\n"
+ " }\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+
+ verifyFormat("MYIF (a) g();", AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g()\n"
+ "};",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b) g();\n"
+ "else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else g();",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) g();\n"
+ "else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) g();\n"
+ "else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else MYIF (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("MYIF (a) {\n"
+ " g();\n"
+ "} else if (b) {\n"
+ " g();\n"
+ "} else {\n"
+ " g();\n"
+ "}",
+ AllowsMergedIf);
+}
+
+TEST_F(FormatTest, WrapMultipleStatementIfAndElseBraces) {
+ auto Style = getLLVMStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_AllIfsAndElse;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ Style.BraceWrapping.BeforeElse = true;
+
+ verifyFormat("if (x)\n"
+ "{\n"
+ " ++x;\n"
+ " --y;\n"
+ "}\n"
+ "else\n"
+ "{\n"
+ " --x;\n"
+ " ++y;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
+ verifyFormat("while (true)\n"
+ " ;");
+ verifyFormat("for (;;)\n"
+ " ;");
+
+ FormatStyle AllowsMergedLoops = getLLVMStyle();
+ AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
+
+ verifyFormat("while (true) continue;", AllowsMergedLoops);
+ verifyFormat("for (;;) continue;", AllowsMergedLoops);
+ verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
+ verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
+ verifyFormat("while (true);", AllowsMergedLoops);
+ verifyFormat("for (;;);", AllowsMergedLoops);
+ verifyFormat("for (;;)\n"
+ " for (;;) continue;",
+ AllowsMergedLoops);
+ verifyFormat("for (;;)\n"
+ " while (true) continue;",
+ AllowsMergedLoops);
+ verifyFormat("while (true)\n"
+ " for (;;) continue;",
+ AllowsMergedLoops);
+ verifyFormat("BOOST_FOREACH (int &v, vec)\n"
+ " for (;;) continue;",
+ AllowsMergedLoops);
+ verifyFormat("for (;;)\n"
+ " BOOST_FOREACH (int &v, vec) continue;",
+ AllowsMergedLoops);
+ verifyFormat("for (;;) // Can't merge this\n"
+ " continue;",
+ AllowsMergedLoops);
+ verifyFormat("for (;;) /* still don't merge */\n"
+ " continue;",
+ AllowsMergedLoops);
+ verifyFormat("do a++;\n"
+ "while (true);",
+ AllowsMergedLoops);
+ verifyFormat("do /* Don't merge */\n"
+ " a++;\n"
+ "while (true);",
+ AllowsMergedLoops);
+ verifyFormat("do // Don't merge\n"
+ " a++;\n"
+ "while (true);",
+ AllowsMergedLoops);
+ verifyFormat("do\n"
+ " // Don't merge\n"
+ " a++;\n"
+ "while (true);",
+ AllowsMergedLoops);
+
+ // Without braces labels are interpreted differently.
+ verifyFormat("{\n"
+ " do\n"
+ " label:\n"
+ " a++;\n"
+ " while (true);\n"
+ "}",
+ AllowsMergedLoops);
+
+ // Don't merge if there are comments before the null statement.
+ verifyFormat("while (1) //\n"
+ " ;",
+ AllowsMergedLoops);
+ verifyFormat("for (;;) /**/\n"
+ " ;",
+ AllowsMergedLoops);
+ verifyFormat("while (true) /**/\n"
+ " ;",
+ "while (true) /**/;", AllowsMergedLoops);
+}
+
+TEST_F(FormatTest, FormatShortBracedStatements) {
+ FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
+ EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
+ EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
+ FormatStyle::SIS_Never);
+ EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
+ EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
+ verifyFormat("for (;;) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("/*comment*/ for (;;) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("while (true) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("/*comment*/ while (true) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("if (true) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("/*comment*/ if (true) {\n"
+ " f();\n"
+ "}");
+
+ AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
+ FormatStyle::SBS_Empty;
+ AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if (i) break;", AllowSimpleBracedStatements);
+ verifyFormat("if (i > 0) {\n"
+ " return i;\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
+ // Where line-lengths matter, a 2-letter synonym that maintains line length.
+ // Not IF to avoid any confusion that IF is somehow special.
+ AllowSimpleBracedStatements.IfMacros.push_back("FI");
+ AllowSimpleBracedStatements.ColumnLimit = 40;
+ AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
+ FormatStyle::SBS_Always;
+ AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
+ AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
+ AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
+ AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if consteval {}", AllowSimpleBracedStatements);
+ verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+ verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if (true) { fffffffffffffffffffffff(); }",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " ffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) { //\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " f();\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " f();\n"
+ "} else {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " ffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) { //\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " f();\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " f();\n"
+ "} else {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ verifyFormat("struct A2 {\n"
+ " int X;\n"
+ "};",
+ AllowSimpleBracedStatements);
+ verifyFormat("typedef struct A2 {\n"
+ " int X;\n"
+ "} A2_t;",
+ AllowSimpleBracedStatements);
+ verifyFormat("template <int> struct A2 {\n"
+ " struct B {};\n"
+ "};",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_Never;
+ verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true) {\n"
+ " f();\n"
+ "} else {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {\n"
+ " f();\n"
+ "} else {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
+ verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("while (true) {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+ verifyFormat("for (;;) {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+ verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
+ AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
+ FormatStyle::BWACS_Always;
+
+ verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+ verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
+ verifyFormat("if (true) { fffffffffffffffffffffff(); }",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " ffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{ //\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " f();\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " f();\n"
+ "} else\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " ffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{ //\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " f();\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " f();\n"
+ "} else\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_Never;
+ verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("if (true)\n"
+ "{\n"
+ " f();\n"
+ "} else\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("MYIF (true)\n"
+ "{\n"
+ " f();\n"
+ "} else\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
+ verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+ verifyFormat("while (true)\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+ verifyFormat("for (;;)\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+ verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+ verifyFormat("BOOST_FOREACH (int v, vec)\n"
+ "{\n"
+ " f();\n"
+ "}",
+ AllowSimpleBracedStatements);
+
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+
+ verifyFormat("while (i > 0)\n"
+ "{\n"
+ " --i;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (a)\n"
+ "{\n"
+ " ++b;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (a)\n"
+ "{\n"
+ " b = 1;\n"
+ "} else\n"
+ "{\n"
+ " b = 0;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (a)\n"
+ "{\n"
+ " b = 1;\n"
+ "} else if (c)\n"
+ "{\n"
+ " b = 2;\n"
+ "} else\n"
+ "{\n"
+ " b = 0;\n"
+ "}",
+ Style);
+
+ Style.BraceWrapping.BeforeElse = true;
+
+ verifyFormat("if (a)\n"
+ "{\n"
+ " b = 1;\n"
+ "}\n"
+ "else\n"
+ "{\n"
+ " b = 0;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (a)\n"
+ "{\n"
+ " b = 1;\n"
+ "}\n"
+ "else if (c)\n"
+ "{\n"
+ " b = 2;\n"
+ "}\n"
+ "else\n"
+ "{\n"
+ " b = 0;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandsMacros) {
+ verifyFormat("#define A (parentheses)");
+ verifyFormat("/* comment */ #define A (parentheses)");
+ verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+ // Even the partial code should never be merged.
+ verifyNoChange("/* comment */ #define A (parentheses)\n"
+ "#");
+ verifyFormat("/* comment */ #define A (parentheses)\n"
+ "#\n");
+ verifyFormat("/* comment */ #define A (parentheses)\n"
+ "#define B (parentheses)");
+ verifyFormat("#define true ((int)1)");
+ verifyFormat("#define and(x)");
+ verifyFormat("#define if(x) x");
+ verifyFormat("#define return(x) (x)");
+ verifyFormat("#define while(x) for (; x;)");
+ verifyFormat("#define xor(x) (^(x))");
+ verifyFormat("#define __except(x)");
+ verifyFormat("#define __try(x)");
+
+ // https://llvm.org/PR54348.
+ verifyFormat(
+ "#define A"
+ " "
+ "\\\n"
+ " class & {}");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ // Test that a macro definition never gets merged with the following
+ // definition.
+ // FIXME: The AAA macro definition probably should not be split into 3 lines.
+ verifyFormat("#define AAA "
+ " \\\n"
+ " N "
+ " \\\n"
+ " {\n"
+ "#define BBB }",
+ Style);
+ // verifyFormat("#define AAA N { //", Style);
+
+ verifyFormat("MACRO(return)");
+ verifyFormat("MACRO(co_await)");
+ verifyFormat("MACRO(co_return)");
+ verifyFormat("MACRO(co_yield)");
+ verifyFormat("MACRO(return, something)");
+ verifyFormat("MACRO(co_return, something)");
+ verifyFormat("MACRO(something##something)");
+ verifyFormat("MACRO(return##something)");
+ verifyFormat("MACRO(co_return##something)");
+
+ verifyFormat("#define A x:");
+
+ verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
+ " { \\\n"
+ " #Bar \\\n"
+ " }");
+ verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
+ " { #Bar }");
+}
+
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+ FormatStyle Style = getLLVMStyleWithColumns(60);
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("#define A \\\n"
+ " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+ " { \\\n"
+ " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+ " }\n"
+ "X;",
+ "#define A \\\n"
+ " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+ " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+ " }\n"
+ "X;",
+ Style);
+}
+
+TEST_F(FormatTest, ParseIfElse) {
+ verifyFormat("if (true)\n"
+ " if (true)\n"
+ " if (true)\n"
+ " f();\n"
+ " else\n"
+ " g();\n"
+ " else\n"
+ " h();\n"
+ "else\n"
+ " i();");
+ verifyFormat("if (true)\n"
+ " if (true)\n"
+ " if (true) {\n"
+ " if (true)\n"
+ " f();\n"
+ " } else {\n"
+ " g();\n"
+ " }\n"
+ " else\n"
+ " h();\n"
+ "else {\n"
+ " i();\n"
+ "}");
+ verifyFormat("if (true)\n"
+ " if constexpr (true)\n"
+ " if (true) {\n"
+ " if constexpr (true)\n"
+ " f();\n"
+ " } else {\n"
+ " g();\n"
+ " }\n"
+ " else\n"
+ " h();\n"
+ "else {\n"
+ " i();\n"
+ "}");
+ verifyFormat("if (true)\n"
+ " if CONSTEXPR (true)\n"
+ " if (true) {\n"
+ " if CONSTEXPR (true)\n"
+ " f();\n"
+ " } else {\n"
+ " g();\n"
+ " }\n"
+ " else\n"
+ " h();\n"
+ "else {\n"
+ " i();\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " if (a) {\n"
+ " } else {\n"
+ " }\n"
+ "}");
+}
+
+TEST_F(FormatTest, ElseIf) {
+ verifyFormat("if (a) {\n} else if (b) {\n}");
+ verifyFormat("if (a)\n"
+ " f();\n"
+ "else if (b)\n"
+ " g();\n"
+ "else\n"
+ " h();");
+ verifyFormat("if (a)\n"
+ " f();\n"
+ "else // comment\n"
+ " if (b) {\n"
+ " g();\n"
+ " h();\n"
+ " }");
+ verifyFormat("if constexpr (a)\n"
+ " f();\n"
+ "else if constexpr (b)\n"
+ " g();\n"
+ "else\n"
+ " h();");
+ verifyFormat("if CONSTEXPR (a)\n"
+ " f();\n"
+ "else if CONSTEXPR (b)\n"
+ " g();\n"
+ "else\n"
+ " h();");
+ verifyFormat("if (a) {\n"
+ " f();\n"
+ "}\n"
+ "// or else ..\n"
+ "else {\n"
+ " g()\n"
+ "}");
+
+ verifyFormat("if (a) {\n"
+ "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
+ "}");
+ verifyFormat("if (a) {\n"
+ "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
+ "}");
+ verifyFormat("if (a) {\n"
+ "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
+ "}");
+ verifyFormat("if (a) {\n"
+ "} else if (\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+ "}",
+ getLLVMStyleWithColumns(62));
+ verifyFormat("if (a) {\n"
+ "} else if constexpr (\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+ "}",
+ getLLVMStyleWithColumns(62));
+ verifyFormat("if (a) {\n"
+ "} else if CONSTEXPR (\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+ "}",
+ getLLVMStyleWithColumns(62));
+}
+
+TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
+ EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
+ verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
+ verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
+ verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
+ verifyFormat("int *f1(int &a) const &;", Style);
+ verifyFormat("int *f1(int &a) const & = 0;", Style);
+ verifyFormat("int *a = f1();", Style);
+ verifyFormat("int &b = f2();", Style);
+ verifyFormat("int &&c = f3();", Style);
+ verifyFormat("int f3() { return sizeof(Foo &); }", Style);
+ verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
+ verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
+ verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
+ verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
+ verifyFormat(
+ "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
+ " res2 = [](int &a) { return 0000000000000; };",
+ Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
+ verifyFormat("Const unsigned int *c;\n"
+ "const unsigned int *d;\n"
+ "Const unsigned int &e;\n"
+ "const unsigned int &f;\n"
+ "int *f1(int *a, int &b, int &&c);\n"
+ "double *(*f2)(int *a, double &&b);\n"
+ "const unsigned &&g;\n"
+ "Const unsigned h;",
+ Style);
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
+ verifyFormat("Const unsigned int *c;\n"
+ "const unsigned int *d;\n"
+ "Const unsigned int &e;\n"
+ "const unsigned int &f;\n"
+ "int *f1(int *a, int &b, int &&c);\n"
+ "double *(*f2)(int *a, double &&b);\n"
+ "const unsigned &&g;\n"
+ "Const unsigned h;",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
+ verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
+ verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
+ verifyFormat("int* f1(int& a) const& = 0;", Style);
+ verifyFormat("int* a = f1();", Style);
+ verifyFormat("int& b = f2();", Style);
+ verifyFormat("int&& c = f3();", Style);
+ verifyFormat("int f3() { return sizeof(Foo&); }", Style);
+ verifyFormat("int f4() { return sizeof(Foo&&); }", Style);
+ verifyFormat("void f5() { int f6(Foo&, Bar&); }", Style);
+ verifyFormat("void f5() { int f6(Foo&&, Bar&&); }", Style);
+ verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
+ verifyFormat(
+ "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
+ " res2 = [](int& a) { return 0000000000000; };",
+ Style);
+ verifyFormat("[](decltype(foo)& Bar) {}", Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
+ verifyFormat("Const unsigned int* c;\n"
+ "const unsigned int* d;\n"
+ "Const unsigned int& e;\n"
+ "const unsigned int& f;\n"
+ "int* f1(int* a, int& b, int&& c);\n"
+ "double* (*f2)(int* a, double&& b);\n"
+ "const unsigned&& g;\n"
+ "Const unsigned h;",
+ Style);
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
+ verifyFormat("Const unsigned int* c;\n"
+ "const unsigned int* d;\n"
+ "Const unsigned int& e;\n"
+ "const unsigned int& f;\n"
+ "int* f1(int* a, int& b, int&& c);\n"
+ "double* (*f2)(int* a, double&& b);\n"
+ "const unsigned&& g;\n"
+ "Const unsigned h;",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Right;
+ Style.ReferenceAlignment = FormatStyle::RAS_Left;
+ verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
+ verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
+ verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
+ verifyFormat("int *a = f1();", Style);
+ verifyFormat("int& b = f2();", Style);
+ verifyFormat("int&& c = f3();", Style);
+ verifyFormat("int f3() { return sizeof(Foo&); }", Style);
+ verifyFormat("int f4() { return sizeof(Foo&&); }", Style);
+ verifyFormat("void f5() { int f6(Foo&, Bar&); }", Style);
+ verifyFormat("void f5() { int f6(Foo&&, Bar&&); }", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
+ verifyFormat("Const unsigned int *c;\n"
+ "const unsigned int *d;\n"
+ "Const unsigned int& e;\n"
+ "const unsigned int& f;\n"
+ "int *f1(int *a, int& b, int&& c);\n"
+ "double *(*f2)(int *a, double&& b);\n"
+ "const unsigned&& g;\n"
+ "Const unsigned h;",
+ Style);
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
+ verifyFormat("Const unsigned int *c;\n"
+ "const unsigned int *d;\n"
+ "Const unsigned int& e;\n"
+ "const unsigned int& f;\n"
+ "int *f1(int *a, int& b, int&& c);\n"
+ "double *(*f2)(int *a, double&& b);\n"
+ "const unsigned&& g;\n"
+ "Const unsigned h;",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ Style.ReferenceAlignment = FormatStyle::RAS_Middle;
+ verifyFormat("int* f1(int* a, int & b, int && c);", Style);
+ verifyFormat("int & f2(int && c, int* a, int & b);", Style);
+ verifyFormat("int && f3(int & b, int && c, int* a);", Style);
+ verifyFormat("int* a = f1();", Style);
+ verifyFormat("int & b = f2();", Style);
+ verifyFormat("int && c = f3();", Style);
+ verifyFormat("int f3() { return sizeof(Foo &); }", Style);
+ verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
+ verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
+ verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
+ verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
+ verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
+ verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
+ verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
+ verifyFormat(
+ "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
+ " res2 = [](int & a) { return 0000000000000; };",
+ Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
+ verifyFormat("Const unsigned int* c;\n"
+ "const unsigned int* d;\n"
+ "Const unsigned int & e;\n"
+ "const unsigned int & f;\n"
+ "int* f1(int* a, int & b, int && c);\n"
+ "double* (*f2)(int* a, double && b);\n"
+ "const unsigned && g;\n"
+ "Const unsigned h;",
+ Style);
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
+ verifyFormat("Const unsigned int* c;\n"
+ "const unsigned int* d;\n"
+ "Const unsigned int & e;\n"
+ "const unsigned int & f;\n"
+ "int* f1(int* a, int & b, int && c);\n"
+ "double* (*f2)(int* a, double && b);\n"
+ "const unsigned && g;\n"
+ "Const unsigned h;",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ Style.ReferenceAlignment = FormatStyle::RAS_Right;
+ verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
+ verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
+ verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
+ verifyFormat("int * a = f1();", Style);
+ verifyFormat("int &b = f2();", Style);
+ verifyFormat("int &&c = f3();", Style);
+ verifyFormat("int f3() { return sizeof(Foo &); }", Style);
+ verifyFormat("int f4() { return sizeof(Foo &&); }", Style);
+ verifyFormat("void f5() { int f6(Foo &, Bar &); }", Style);
+ verifyFormat("void f5() { int f6(Foo &&, Bar &&); }", Style);
+ verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
+ verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = true;
+ verifyFormat("Const unsigned int * c;\n"
+ "const unsigned int * d;\n"
+ "Const unsigned int &e;\n"
+ "const unsigned int &f;\n"
+ "int * f1(int * a, int &b, int &&c);\n"
+ "double * (*f2)(int * a, double &&b);\n"
+ "const unsigned &&g;\n"
+ "Const unsigned h;",
+ Style);
+ Style.AlignConsecutiveDeclarations.AlignFunctionPointers = false;
+ verifyFormat("Const unsigned int * c;\n"
+ "const unsigned int * d;\n"
+ "Const unsigned int &e;\n"
+ "const unsigned int &f;\n"
+ "int * f1(int * a, int &b, int &&c);\n"
+ "double * (*f2)(int * a, double &&b);\n"
+ "const unsigned &&g;\n"
+ "Const unsigned h;",
+ Style);
+
+ // FIXME: we don't handle this yet, so output may be arbitrary until it's
+ // specifically handled
+ // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
+}
+
+TEST_F(FormatTest, FormatsForLoop) {
+ verifyFormat(
+ "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
+ " ++VeryVeryLongLoopVariable)\n"
+ " ;");
+ verifyFormat("for (;;)\n"
+ " f();");
+ verifyFormat("for (;;) {\n}");
+ verifyFormat("for (;;) {\n"
+ " f();\n"
+ "}");
+ verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
+
+ verifyFormat(
+ "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
+ " E = UnwrappedLines.end();\n"
+ " I != E; ++I) {\n}");
+
+ verifyFormat(
+ "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
+ " ++IIIII) {\n}");
+ verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
+ " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
+ verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
+ " I = FD->getDeclsInPrototypeScope().begin(),\n"
+ " E = FD->getDeclsInPrototypeScope().end();\n"
+ " I != E; ++I) {\n}");
+ verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
+ " I = Container.begin(),\n"
+ " E = Container.end();\n"
+ " I != E; ++I) {\n}",
+ getLLVMStyleWithColumns(76));
+
+ verifyFormat(
+ "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
+ " ++aaaaaaaaaaa) {\n}");
+ verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
+ " ++i) {\n}");
+ verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
+ " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
+ "}");
+ verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
+ " aaaaaaaaaa);\n"
+ " iter; ++iter) {\n"
+ "}");
+ verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
+ " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
+
+ // These should not be formatted as Objective-C for-in loops.
+ verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
+ verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
+ verifyFormat("Foo *x;\nfor (x in y) {\n}");
+ verifyFormat(
+ "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
+
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("for (int aaaaaaaaaaa = 1;\n"
+ " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa);\n"
+ " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
+ "}",
+ NoBinPacking);
+ verifyFormat(
+ "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
+ " E = UnwrappedLines.end();\n"
+ " I != E;\n"
+ " ++I) {\n}",
+ NoBinPacking);
+
+ FormatStyle AlignLeft = getLLVMStyle();
+ AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
+}
+
+TEST_F(FormatTest, RangeBasedForLoops) {
+ verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
+ verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
+ verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
+ verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
+}
+
+TEST_F(FormatTest, ForEachLoops) {
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+ EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
+ verifyFormat("void f() {\n"
+ " for (;;) {\n"
+ " }\n"
+ " foreach (Item *item, itemlist) {\n"
+ " }\n"
+ " Q_FOREACH (Item *item, itemlist) {\n"
+ " }\n"
+ " BOOST_FOREACH (Item *item, itemlist) {\n"
+ " }\n"
+ " UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
+ "}",
+ Style);
+ verifyFormat("void f() {\n"
+ " for (;;)\n"
+ " int j = 1;\n"
+ " Q_FOREACH (int v, vec)\n"
+ " v *= 2;\n"
+ " for (;;) {\n"
+ " int j = 1;\n"
+ " }\n"
+ " Q_FOREACH (int v, vec) {\n"
+ " v *= 2;\n"
+ " }\n"
+ "}",
+ Style);
+
+ FormatStyle ShortBlocks = getLLVMStyle();
+ ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
+ verifyFormat("void f() {\n"
+ " for (;;)\n"
+ " int j = 1;\n"
+ " Q_FOREACH (int &v, vec)\n"
+ " v *= 2;\n"
+ " for (;;) {\n"
+ " int j = 1;\n"
+ " }\n"
+ " Q_FOREACH (int &v, vec) {\n"
+ " int j = 1;\n"
+ " }\n"
+ "}",
+ ShortBlocks);
+
+ FormatStyle ShortLoops = getLLVMStyle();
+ ShortLoops.AllowShortLoopsOnASingleLine = true;
+ EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+ verifyFormat("void f() {\n"
+ " for (;;) int j = 1;\n"
+ " Q_FOREACH (int &v, vec) int j = 1;\n"
+ " for (;;) {\n"
+ " int j = 1;\n"
+ " }\n"
+ " Q_FOREACH (int &v, vec) {\n"
+ " int j = 1;\n"
+ " }\n"
+ "}",
+ ShortLoops);
+
+ FormatStyle ShortBlocksAndLoops = getLLVMStyle();
+ ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
+ verifyFormat("void f() {\n"
+ " for (;;) int j = 1;\n"
+ " Q_FOREACH (int &v, vec) int j = 1;\n"
+ " for (;;) { int j = 1; }\n"
+ " Q_FOREACH (int &v, vec) { int j = 1; }\n"
+ "}",
+ ShortBlocksAndLoops);
+
+ Style.SpaceBeforeParens =
+ FormatStyle::SBPO_ControlStatementsExceptControlMacros;
+ verifyFormat("void f() {\n"
+ " for (;;) {\n"
+ " }\n"
+ " foreach(Item *item, itemlist) {\n"
+ " }\n"
+ " Q_FOREACH(Item *item, itemlist) {\n"
+ " }\n"
+ " BOOST_FOREACH(Item *item, itemlist) {\n"
+ " }\n"
+ " UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
+ "}",
+ Style);
+
+ // As function-like macros.
+ verifyFormat("#define foreach(x, y)\n"
+ "#define Q_FOREACH(x, y)\n"
+ "#define BOOST_FOREACH(x, y)\n"
+ "#define UNKNOWN_FOREACH(x, y)");
+
+ // Not as function-like macros.
+ verifyFormat("#define foreach (x, y)\n"
+ "#define Q_FOREACH (x, y)\n"
+ "#define BOOST_FOREACH (x, y)\n"
+ "#define UNKNOWN_FOREACH (x, y)");
+
+ // handle microsoft non standard extension
+ verifyFormat("for each (char c in x->MyStringProperty)");
+}
+
+TEST_F(FormatTest, FormatsWhileLoop) {
+ verifyFormat("while (true) {\n}");
+ verifyFormat("while (true)\n"
+ " f();");
+ verifyFormat("while () {\n}");
+ verifyFormat("while () {\n"
+ " f();\n"
+ "}");
+}
+
+TEST_F(FormatTest, FormatsDoWhile) {
+ verifyFormat("do {\n"
+ " do_something();\n"
+ "} while (something());");
+ verifyFormat("do\n"
+ " do_something();\n"
+ "while (something());");
+}
+
+TEST_F(FormatTest, FormatsSwitchStatement) {
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ " f();\n"
+ " break;\n"
+ "case kFoo:\n"
+ "case ns::kBar:\n"
+ "case kBaz:\n"
+ " break;\n"
+ "default:\n"
+ " g();\n"
+ " break;\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1: {\n"
+ " f();\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " break;\n"
+ "}\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1: {\n"
+ " f();\n"
+ " {\n"
+ " g();\n"
+ " h();\n"
+ " }\n"
+ " break;\n"
+ "}\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1: {\n"
+ " f();\n"
+ " if (foo) {\n"
+ " g();\n"
+ " h();\n"
+ " }\n"
+ " break;\n"
+ "}\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1: {\n"
+ " f();\n"
+ " g();\n"
+ "} break;\n"
+ "}");
+ verifyFormat("switch (test)\n"
+ " ;");
+ verifyFormat("switch (x) {\n"
+ "default: {\n"
+ " // Do nothing.\n"
+ "}\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "// comment\n"
+ "// if 1, do f()\n"
+ "case 1:\n"
+ " f();\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ " // Do amazing stuff\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ " break;\n"
+ "}");
+ verifyFormat("#define A \\\n"
+ " switch (x) { \\\n"
+ " case a: \\\n"
+ " foo = b; \\\n"
+ " }",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("#define OPERATION_CASE(name) \\\n"
+ " case OP_name: \\\n"
+ " return operations::Operation##name",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("switch (x) {\n"
+ "case 1:;\n"
+ "default:;\n"
+ " int i;\n"
+ "}");
+
+ verifyGoogleFormat("switch (x) {\n"
+ " case 1:\n"
+ " f();\n"
+ " break;\n"
+ " case kFoo:\n"
+ " case ns::kBar:\n"
+ " case kBaz:\n"
+ " break;\n"
+ " default:\n"
+ " g();\n"
+ " break;\n"
+ "}");
+ verifyGoogleFormat("switch (x) {\n"
+ " case 1: {\n"
+ " f();\n"
+ " break;\n"
+ " }\n"
+ "}");
+ verifyGoogleFormat("switch (test)\n"
+ " ;");
+
+ verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
+ " case OP_name: \\\n"
+ " return operations::Operation##name");
+ verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
+ " // Get the correction operation class.\n"
+ " switch (OpCode) {\n"
+ " CASE(Add);\n"
+ " CASE(Subtract);\n"
+ " default:\n"
+ " return operations::Unknown;\n"
+ " }\n"
+ "#undef OPERATION_CASE\n"
+ "}");
+ verifyFormat("DEBUG({\n"
+ " switch (x) {\n"
+ " case A:\n"
+ " f();\n"
+ " break;\n"
+ " // fallthrough\n"
+ " case B:\n"
+ " g();\n"
+ " break;\n"
+ " }\n"
+ "});");
+ verifyNoChange("DEBUG({\n"
+ " switch (x) {\n"
+ " case A:\n"
+ " f();\n"
+ " break;\n"
+ " // On B:\n"
+ " case B:\n"
+ " g();\n"
+ " break;\n"
+ " }\n"
+ "});");
+ verifyFormat("switch (n) {\n"
+ "case 0: {\n"
+ " return false;\n"
+ "}\n"
+ "default: {\n"
+ " return true;\n"
+ "}\n"
+ "}",
+ "switch (n)\n"
+ "{\n"
+ "case 0: {\n"
+ " return false;\n"
+ "}\n"
+ "default: {\n"
+ " return true;\n"
+ "}\n"
+ "}");
+ verifyFormat("switch (a) {\n"
+ "case (b):\n"
+ " return;\n"
+ "}");
+
+ verifyFormat("switch (a) {\n"
+ "case some_namespace::\n"
+ " some_constant:\n"
+ " return;\n"
+ "}",
+ getLLVMStyleWithColumns(34));
+
+ verifyFormat("switch (a) {\n"
+ "[[likely]] case 1:\n"
+ " return;\n"
+ "}");
+ verifyFormat("switch (a) {\n"
+ "[[likely]] [[other::likely]] case 1:\n"
+ " return;\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ " return;\n"
+ "[[likely]] case 2:\n"
+ " return;\n"
+ "}");
+ verifyFormat("switch (a) {\n"
+ "case 1:\n"
+ "[[likely]] case 2:\n"
+ " return;\n"
+ "}");
+ FormatStyle Attributes = getLLVMStyle();
+ Attributes.AttributeMacros.push_back("LIKELY");
+ Attributes.AttributeMacros.push_back("OTHER_LIKELY");
+ verifyFormat("switch (a) {\n"
+ "LIKELY case b:\n"
+ " return;\n"
+ "}",
+ Attributes);
+ verifyFormat("switch (a) {\n"
+ "LIKELY OTHER_LIKELY() case b:\n"
+ " return;\n"
+ "}",
+ Attributes);
+ verifyFormat("switch (a) {\n"
+ "case 1:\n"
+ " return;\n"
+ "LIKELY case 2:\n"
+ " return;\n"
+ "}",
+ Attributes);
+ verifyFormat("switch (a) {\n"
+ "case 1:\n"
+ "LIKELY case 2:\n"
+ " return;\n"
+ "}",
+ Attributes);
+
+ FormatStyle Style = getLLVMStyle();
+ Style.IndentCaseLabels = true;
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterCaseLabel = true;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ verifyFormat("switch (n)\n"
+ "{\n"
+ " case 0:\n"
+ " {\n"
+ " return false;\n"
+ " }\n"
+ " default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ "switch (n) {\n"
+ " case 0: {\n"
+ " return false;\n"
+ " }\n"
+ " default: {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ Style);
+ Style.BraceWrapping.AfterCaseLabel = false;
+ verifyFormat("switch (n)\n"
+ "{\n"
+ " case 0: {\n"
+ " return false;\n"
+ " }\n"
+ " default: {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ "switch (n) {\n"
+ " case 0:\n"
+ " {\n"
+ " return false;\n"
+ " }\n"
+ " default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ Style);
+ Style.IndentCaseLabels = false;
+ Style.IndentCaseBlocks = true;
+ verifyFormat("switch (n)\n"
+ "{\n"
+ "case 0:\n"
+ " {\n"
+ " return false;\n"
+ " }\n"
+ "case 1:\n"
+ " break;\n"
+ "default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ "switch (n) {\n"
+ "case 0: {\n"
+ " return false;\n"
+ "}\n"
+ "case 1:\n"
+ " break;\n"
+ "default: {\n"
+ " return true;\n"
+ "}\n"
+ "}",
+ Style);
+ Style.IndentCaseLabels = true;
+ Style.IndentCaseBlocks = true;
+ verifyFormat("switch (n)\n"
+ "{\n"
+ " case 0:\n"
+ " {\n"
+ " return false;\n"
+ " }\n"
+ " case 1:\n"
+ " break;\n"
+ " default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ "switch (n) {\n"
+ "case 0: {\n"
+ " return false;\n"
+ "}\n"
+ "case 1:\n"
+ " break;\n"
+ "default: {\n"
+ " return true;\n"
+ "}\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, CaseRanges) {
+ verifyFormat("switch (x) {\n"
+ "case 'A' ... 'Z':\n"
+ "case 1 ... 5:\n"
+ "case a ... b:\n"
+ " break;\n"
+ "}");
+}
+
+TEST_F(FormatTest, ShortEnums) {
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
+ EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
+ verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
+ verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
+ Style.AllowShortEnumsOnASingleLine = false;
+ verifyFormat("enum {\n"
+ " A,\n"
+ " B,\n"
+ " C\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+ verifyFormat("typedef enum {\n"
+ " A,\n"
+ " B,\n"
+ " C\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+ verifyFormat("enum {\n"
+ " A,\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+ verifyFormat("typedef enum {\n"
+ " A,\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterEnum = true;
+ verifyFormat("enum\n"
+ "{\n"
+ " A,\n"
+ " B,\n"
+ " C\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+ verifyFormat("typedef enum\n"
+ "{\n"
+ " A,\n"
+ " B,\n"
+ " C\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+
+ Style.AllowShortEnumsOnASingleLine = true;
+ verifyFormat("export enum\n"
+ "{\n"
+ " A,\n"
+ " B,\n"
+ " C\n"
+ "} ShortEnum1, ShortEnum2;",
+ Style);
+}
+
+TEST_F(FormatTest, ShortCompoundRequirement) {
+ constexpr StringRef Code("template <typename T>\n"
+ "concept c = requires(T x) {\n"
+ " { x + 1 } -> std::same_as<int>;\n"
+ "};");
+
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_TRUE(Style.AllowShortCompoundRequirementOnASingleLine);
+ verifyFormat(Code, Style);
+ verifyFormat("template <typename T>\n"
+ "concept c = requires(T x) {\n"
+ " { x + 1 } -> std::same_as<int>;\n"
+ " { x + 2 } -> std::same_as<int>;\n"
+ "};",
+ Style);
+
+ Style.AllowShortCompoundRequirementOnASingleLine = false;
+ verifyFormat("template <typename T>\n"
+ "concept c = requires(T x) {\n"
+ " {\n"
+ " x + 1\n"
+ " } -> std::same_as<int>;\n"
+ "};",
+ Code, Style);
+ verifyFormat("template <typename T>\n"
+ "concept c = requires(T x) {\n"
+ " {\n"
+ " x + 1\n"
+ " } -> std::same_as<int>;\n"
+ " {\n"
+ " x + 2\n"
+ " } -> std::same_as<int>;\n"
+ "};",
+ Style);
+
+ Style.AllowShortCompoundRequirementOnASingleLine = true;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
+ verifyFormat(Code, Style);
+}
+
+TEST_F(FormatTest, ShortCaseLabels) {
+ FormatStyle Style = getLLVMStyle();
+ Style.AllowShortCaseLabelsOnASingleLine = true;
+ verifyFormat("switch (a) {\n"
+ "case 1: x = 1; break;\n"
+ "case 2: return;\n"
+ "case 3:\n"
+ "case 4:\n"
+ "case 5: return;\n"
+ "case 6: // comment\n"
+ " return;\n"
+ "case 7:\n"
+ " // comment\n"
+ " return;\n"
+ "case 8:\n"
+ " x = 8; // comment\n"
+ " break;\n"
+ "default: y = 1; break;\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 0: return; // comment\n"
+ "case 1: break; // comment\n"
+ "case 2: return;\n"
+ "// comment\n"
+ "case 3: return;\n"
+ "// comment 1\n"
+ "// comment 2\n"
+ "// comment 3\n"
+ "case 4: break; /* comment */\n"
+ "case 5:\n"
+ " // comment\n"
+ " break;\n"
+ "case 6: /* comment */ x = 1; break;\n"
+ "case 7: x = /* comment */ 1; break;\n"
+ "case 8:\n"
+ " x = 1; /* comment */\n"
+ " break;\n"
+ "case 9:\n"
+ " break; // comment line 1\n"
+ " // comment line 2\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 1:\n"
+ " x = 8;\n"
+ " // fall through\n"
+ "case 2: x = 8;\n"
+ "// comment\n"
+ "case 3:\n"
+ " return; /* comment line 1\n"
+ " * comment line 2 */\n"
+ "case 4: i = 8;\n"
+ "// something else\n"
+ "#if FOO\n"
+ "case 5: break;\n"
+ "#endif\n"
+ "}",
+ "switch (a) {\n"
+ "case 1: x = 8;\n"
+ " // fall through\n"
+ "case 2:\n"
+ " x = 8;\n"
+ "// comment\n"
+ "case 3:\n"
+ " return; /* comment line 1\n"
+ " * comment line 2 */\n"
+ "case 4:\n"
+ " i = 8;\n"
+ "// something else\n"
+ "#if FOO\n"
+ "case 5: break;\n"
+ "#endif\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 0:\n"
+ " return; // long long long long long long long long long long "
+ "long long comment\n"
+ " // line\n"
+ "}",
+ "switch (a) {\n"
+ "case 0: return; // long long long long long long long long "
+ "long long long long comment line\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 0:\n"
+ " return; /* long long long long long long long long long long "
+ "long long comment\n"
+ " line */\n"
+ "}",
+ "switch (a) {\n"
+ "case 0: return; /* long long long long long long long long "
+ "long long long long comment line */\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "#if FOO\n"
+ "case 0: return 0;\n"
+ "#endif\n"
+ "}",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 1: {\n"
+ "}\n"
+ "case 2: {\n"
+ " return;\n"
+ "}\n"
+ "case 3: {\n"
+ " x = 1;\n"
+ " return;\n"
+ "}\n"
+ "case 4:\n"
+ " if (x)\n"
+ " return;\n"
+ "}",
+ Style);
+ Style.ColumnLimit = 21;
+ verifyFormat("#define X \\\n"
+ " case 0: break;\n"
+ "#include \"f\"",
+ Style);
+ verifyFormat("switch (a) {\n"
+ "case 1: x = 1; break;\n"
+ "case 2: return;\n"
+ "case 3:\n"
+ "case 4:\n"
+ "case 5: return;\n"
+ "default:\n"
+ " y = 1;\n"
+ " break;\n"
+ "}",
+ Style);
+ Style.ColumnLimit = 80;
+ Style.AllowShortCaseLabelsOnASingleLine = false;
+ Style.IndentCaseLabels = true;
+ verifyFormat("switch (n) {\n"
+ " default /*comments*/:\n"
+ " return true;\n"
+ " case 0:\n"
+ " return false;\n"
+ "}",
+ "switch (n) {\n"
+ "default/*comments*/:\n"
+ " return true;\n"
+ "case 0:\n"
+ " return false;\n"
+ "}",
+ Style);
+ Style.AllowShortCaseLabelsOnASingleLine = true;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterCaseLabel = true;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ verifyFormat("switch (n)\n"
+ "{\n"
+ " case 0:\n"
+ " {\n"
+ " return false;\n"
+ " }\n"
+ " default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ "switch (n) {\n"
+ " case 0: {\n"
+ " return false;\n"
+ " }\n"
+ " default:\n"
+ " {\n"
+ " return true;\n"
+ " }\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsLabels) {
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ "test_label:\n"
+ " some_other_code();\n"
+ " {\n"
+ " some_more_code();\n"
+ " another_label:\n"
+ " some_more_code();\n"
+ " }\n"
+ "}");
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label:\n"
+ " some_other_code();\n"
+ "}");
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label:;\n"
+ " int i = 0;\n"
+ "}");
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label: { some_other_code(); }\n"
+ "}");
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label: {\n"
+ " some_other_code();\n"
+ " some_other_code();\n"
+ "}\n"
+ "}");
+ verifyFormat("{\n"
+ "L0:\n"
+ "[[foo]] L1:\n"
+ "[[bar]] [[baz]] L2:\n"
+ " g();\n"
+ "}");
+ verifyFormat("{\n"
+ "[[foo]] L1: {\n"
+ "[[bar]] [[baz]] L2:\n"
+ " g();\n"
+ "}\n"
+ "}");
+ verifyFormat("{\n"
+ "[[foo]] L1:\n"
+ " f();\n"
+ " {\n"
+ " [[bar]] [[baz]] L2:\n"
+ " g();\n"
+ " }\n"
+ "}");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.IndentGotoLabels = FormatStyle::IGLS_NoIndent;
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ "test_label:\n"
+ " some_other_code();\n"
+ " {\n"
+ " some_more_code();\n"
+ "another_label:\n"
+ " some_more_code();\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label:\n"
+ " some_other_code();\n"
+ "}",
+ Style);
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label:;\n"
+ " int i = 0;\n"
+ "}",
+ Style);
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label: { some_other_code(); }\n"
+ "}",
+ Style);
+ verifyFormat("{\n"
+ "[[foo]] L1:\n"
+ " f();\n"
+ " {\n"
+ "[[bar]] [[baz]] L2:\n"
+ " g();\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("void f() {\n"
+ "L1:\n"
+ " a();\n"
+ " {\n"
+ "L2:\n"
+ " b();\n"
+ " {\n"
+ "L3:\n"
+ " c();\n"
+ " {\n"
+ "L4:\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}",
+ Style);
+ Style.IndentGotoLabels = FormatStyle::IGLS_OuterIndent;
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ "test_label:\n"
+ " some_other_code();\n"
+ " {\n"
+ " some_more_code();\n"
+ " another_label:\n"
+ " some_more_code();\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("void f() {\n"
+ "L1:\n"
+ " a();\n"
+ " {\n"
+ " L2:\n"
+ " b();\n"
+ " {\n"
+ " L3:\n"
+ " c();\n"
+ " {\n"
+ " L4:\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}",
+ Style);
+ Style.IndentGotoLabels = FormatStyle::IGLS_InnerIndent;
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ " test_label:\n"
+ " some_other_code();\n"
+ " {\n"
+ " some_more_code();\n"
+ " another_label:\n"
+ " some_more_code();\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("void f() {\n"
+ " L1:\n"
+ " a();\n"
+ " {\n"
+ " L2:\n"
+ " b();\n"
+ " {\n"
+ " L3:\n"
+ " c();\n"
+ " {\n"
+ " L4:\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}",
+ Style);
+ Style.IndentGotoLabels = FormatStyle::IGLS_HalfIndent;
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ " test_label:\n"
+ " some_other_code();\n"
+ " {\n"
+ " some_more_code();\n"
+ " another_label:\n"
+ " some_more_code();\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("void f() {\n"
+ " L1:\n"
+ " a();\n"
+ " {\n"
+ " L2:\n"
+ " b();\n"
+ " {\n"
+ " L3:\n"
+ " c();\n"
+ " {\n"
+ " L4:\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}",
+ Style);
+ Style.IndentWidth = 3;
+ verifyFormat("void f() {\n"
+ " some_code();\n"
+ " test_label:\n"
+ " some_other_code();\n"
+ "}",
+ Style);
+ Style.IndentWidth = 2;
+ Style.IndentGotoLabels = FormatStyle::IGLS_NoIndent;
+
+ Style.ColumnLimit = 15;
+ verifyFormat("#define FOO \\\n"
+ "label: \\\n"
+ " break;",
+ Style);
+
+ // The opening brace may either be on the same unwrapped line as the colon or
+ // on a separate one. The formatter should recognize both.
+ Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("{\n"
+ " some_code();\n"
+ "test_label:\n"
+ "{\n"
+ " some_other_code();\n"
+ "}\n"
+ "}",
+ Style);
+ verifyFormat("{\n"
+ "[[foo]] L1:\n"
+ "{\n"
+ "[[bar]] [[baz]] L2:\n"
+ " g();\n"
+ "}\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, MultiLineControlStatements) {
+ FormatStyle Style = getLLVMStyleWithColumns(20);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
+ // Short lines should keep opening brace on same line.
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "}",
+ "if(foo){bar();}", Style);
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "} else {\n"
+ " baz();\n"
+ "}",
+ "if(foo){bar();}else{baz();}", Style);
+ verifyFormat("if (foo && bar) {\n"
+ " baz();\n"
+ "}",
+ "if(foo&&bar){baz();}", Style);
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "} else if (baz) {\n"
+ " quux();\n"
+ "}",
+ "if(foo){bar();}else if(baz){quux();}", Style);
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "} else if (baz) {\n"
+ " quux();\n"
+ "} else {\n"
+ " foobar();\n"
+ "}",
+ "if(foo){bar();}else if(baz){quux();}else{foobar();}", Style);
+ verifyFormat("for (;;) {\n"
+ " foo();\n"
+ "}",
+ "for(;;){foo();}");
+ verifyFormat("while (1) {\n"
+ " foo();\n"
+ "}",
+ "while(1){foo();}", Style);
+ verifyFormat("switch (foo) {\n"
+ "case bar:\n"
+ " return;\n"
+ "}",
+ "switch(foo){case bar:return;}", Style);
+ verifyFormat("try {\n"
+ " foo();\n"
+ "} catch (...) {\n"
+ " bar();\n"
+ "}",
+ "try{foo();}catch(...){bar();}", Style);
+ verifyFormat("do {\n"
+ " foo();\n"
+ "} while (bar &&\n"
+ " baz);",
+ "do{foo();}while(bar&&baz);", Style);
+ // Long lines should put opening brace on new line.
+ verifyFormat("void f() {\n"
+ " if (a1 && a2 &&\n"
+ " a3)\n"
+ " {\n"
+ " quux();\n"
+ " }\n"
+ "}",
+ "void f(){if(a1&&a2&&a3){quux();}}", Style);
+ verifyFormat("if (foo && bar &&\n"
+ " baz)\n"
+ "{\n"
+ " quux();\n"
+ "}",
+ "if(foo&&bar&&baz){quux();}", Style);
+ verifyFormat("if (foo && bar &&\n"
+ " baz)\n"
+ "{\n"
+ " quux();\n"
+ "}",
+ "if (foo && bar &&\n"
+ " baz) {\n"
+ " quux();\n"
+ "}",
+ Style);
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "} else if (baz ||\n"
+ " quux)\n"
+ "{\n"
+ " foobar();\n"
+ "}",
+ "if(foo){bar();}else if(baz||quux){foobar();}", Style);
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "} else if (baz ||\n"
+ " quux)\n"
+ "{\n"
+ " foobar();\n"
+ "} else {\n"
+ " barbaz();\n"
+ "}",
+ "if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
+ Style);
+ verifyFormat("for (int i = 0;\n"
+ " i < 10; ++i)\n"
+ "{\n"
+ " foo();\n"
+ "}",
+ "for(int i=0;i<10;++i){foo();}", Style);
+ verifyFormat("foreach (int i,\n"
+ " list)\n"
+ "{\n"
+ " foo();\n"
+ "}",
+ "foreach(int i, list){foo();}", Style);
+ Style.ColumnLimit =
+ 40; // to concentrate at brace wrapping, not line wrap due to column limit
+ verifyFormat("foreach (int i, list) {\n"
+ " foo();\n"
+ "}",
+ "foreach(int i, list){foo();}", Style);
+ Style.ColumnLimit =
+ 20; // to concentrate at brace wrapping, not line wrap due to column limit
+ verifyFormat("while (foo || bar ||\n"
+ " baz)\n"
+ "{\n"
+ " quux();\n"
+ "}",
+ "while(foo||bar||baz){quux();}", Style);
+ verifyFormat("switch (\n"
+ " foo = barbaz)\n"
+ "{\n"
+ "case quux:\n"
+ " return;\n"
+ "}",
+ "switch(foo=barbaz){case quux:return;}", Style);
+ verifyFormat("try {\n"
+ " foo();\n"
+ "} catch (\n"
+ " Exception &bar)\n"
+ "{\n"
+ " baz();\n"
+ "}",
+ "try{foo();}catch(Exception&bar){baz();}", Style);
+ Style.ColumnLimit =
+ 40; // to concentrate at brace wrapping, not line wrap due to column limit
+ verifyFormat("try {\n"
+ " foo();\n"
+ "} catch (Exception &bar) {\n"
+ " baz();\n"
+ "}",
+ "try{foo();}catch(Exception&bar){baz();}", Style);
+ Style.ColumnLimit =
+ 20; // to concentrate at brace wrapping, not line wrap due to column limit
+
+ Style.BraceWrapping.BeforeElse = true;
+ verifyFormat("if (foo) {\n"
+ " bar();\n"
+ "}\n"
+ "else if (baz ||\n"
+ " quux)\n"
+ "{\n"
+ " foobar();\n"
+ "}\n"
+ "else {\n"
+ " barbaz();\n"
+ "}",
+ "if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
+ Style);
+
+ Style.BraceWrapping.BeforeCatch = true;
+ verifyFormat("try {\n"
+ " foo();\n"
+ "}\n"
+ "catch (...) {\n"
+ " baz();\n"
+ "}",
+ "try{foo();}catch(...){baz();}", Style);
+
+ Style.BraceWrapping.AfterFunction = true;
+ Style.BraceWrapping.AfterStruct = false;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ Style.ColumnLimit = 80;
+ verifyFormat("void shortfunction() { bar(); }", Style);
+ verifyFormat("struct T shortfunction() { return bar(); }", Style);
+ verifyFormat("struct T {};", Style);
+
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ verifyFormat("void shortfunction()\n"
+ "{\n"
+ " bar();\n"
+ "}",
+ Style);
+ verifyFormat("struct T shortfunction()\n"
+ "{\n"
+ " return bar();\n"
+ "}",
+ Style);
+ verifyFormat("struct T {};", Style);
+
+ Style.BraceWrapping.AfterFunction = false;
+ Style.BraceWrapping.AfterStruct = true;
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ verifyFormat("void shortfunction() { bar(); }", Style);
+ verifyFormat("struct T shortfunction() { return bar(); }", Style);
+ verifyFormat("struct T\n"
+ "{\n"
+ "};",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ verifyFormat("void shortfunction() {\n"
+ " bar();\n"
+ "}",
+ Style);
+ verifyFormat("struct T shortfunction() {\n"
+ " return bar();\n"
+ "}",
+ Style);
+ verifyFormat("struct T\n"
+ "{\n"
+ "};",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
+ Style.AllowShortLoopsOnASingleLine = true;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
+ verifyFormat("if (true) { return; }", Style);
+ verifyFormat("while (true) { return; }", Style);
+ // Failing test in https://reviews.llvm.org/D114521#3151727
+ verifyFormat("for (;;) { bar(); }", Style);
+}
+
+TEST_F(FormatTest, BeforeWhile) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+
+ verifyFormat("do {\n"
+ " foo();\n"
+ "} while (1);",
+ Style);
+ Style.BraceWrapping.BeforeWhile = true;
+ verifyFormat("do {\n"
+ " foo();\n"
+ "}\n"
+ "while (1);",
+ Style);
+}
+
+//===----------------------------------------------------------------------===//
+// Tests for classes, namespaces, etc.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
+ verifyFormat("class A {};");
+}
+
+TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
+ verifyFormat("class A {\n"
+ "public:\n"
+ "public: // comment\n"
+ "protected:\n"
+ "private:\n"
+ " void f() {}\n"
+ "};");
+ verifyFormat("export class A {\n"
+ "public:\n"
+ "public: // comment\n"
+ "protected:\n"
+ "private:\n"
+ " void f() {}\n"
+ "};");
+ verifyGoogleFormat("class A {\n"
+ " public:\n"
+ " protected:\n"
+ " private:\n"
+ " void f() {}\n"
+ "};");
+ verifyGoogleFormat("export class A {\n"
+ " public:\n"
+ " protected:\n"
+ " private:\n"
+ " void f() {}\n"
+ "};");
+ verifyFormat("class A {\n"
+ "public slots:\n"
+ " void f1() {}\n"
+ "public Q_SLOTS:\n"
+ " void f2() {}\n"
+ "protected slots:\n"
+ " void f3() {}\n"
+ "protected Q_SLOTS:\n"
+ " void f4() {}\n"
+ "private slots:\n"
+ " void f5() {}\n"
+ "private Q_SLOTS:\n"
+ " void f6() {}\n"
+ "signals:\n"
+ " void g1();\n"
+ "Q_SIGNALS:\n"
+ " void g2();\n"
+ "};");
+
+ // Don't interpret 'signals' the wrong way.
+ verifyFormat("signals.set();");
+ verifyFormat("for (Signals signals : f()) {\n}");
+ verifyFormat("{\n"
+ " signals.set(); // This needs indentation.\n"
+ "}");
+ verifyFormat("void f() {\n"
+ "label:\n"
+ " signals.baz();\n"
+ "}");
+
+ const auto Style = getLLVMStyle(FormatStyle::LK_C);
+ verifyFormat("private[1];", Style);
+ verifyFormat("testArray[public] = 1;");
+ verifyFormat("public();", Style);
+ verifyFormat("myFunc(public);");
+ verifyFormat("std::vector<int> testVec = {private};");
+ verifyFormat("private.p = 1;", Style);
+ verifyFormat("void function(private...) {};");
+ verifyFormat("if (private && public)");
+ verifyFormat("private &= true;", Style);
+ verifyFormat("int x = private * public;");
+ verifyFormat("public *= private;", Style);
+ verifyFormat("int x = public + private;");
+ verifyFormat("private++;", Style);
+ verifyFormat("++private;");
+ verifyFormat("public += private;", Style);
+ verifyFormat("public = public - private;", Style);
+ verifyFormat("public->foo();", Style);
+ verifyFormat("private--;", Style);
+ verifyFormat("--private;");
+ verifyFormat("public -= 1;", Style);
+ verifyFormat("if (!private && !public)");
+ verifyFormat("public != private;", Style);
+ verifyFormat("int x = public / private;");
+ verifyFormat("public /= 2;", Style);
+ verifyFormat("public = public % 2;", Style);
+ verifyFormat("public %= 2;", Style);
+ verifyFormat("if (public < private)");
+ verifyFormat("public << private;", Style);
+ verifyFormat("public <<= private;", Style);
+ verifyFormat("if (public > private)");
+ verifyFormat("public >> private;", Style);
+ verifyFormat("public >>= private;", Style);
+ verifyFormat("public ^ private;", Style);
+ verifyFormat("public ^= private;", Style);
+ verifyFormat("public | private;", Style);
+ verifyFormat("public |= private;", Style);
+ verifyFormat("auto x = private ? 1 : 2;");
+ verifyFormat("if (public == private)");
+ verifyFormat("void foo(public, private)");
+
+ verifyFormat("class A {\n"
+ "public:\n"
+ " std::unique_ptr<int *[]> b() { return nullptr; }\n"
+ "\n"
+ "private:\n"
+ " int c;\n"
+ "};\n"
+ "class B {\n"
+ "public:\n"
+ " std::unique_ptr<int *[] /* okay */> b() { return nullptr; }\n"
+ "\n"
+ "private:\n"
+ " int c;\n"
+ "};");
+}
+
+TEST_F(FormatTest, SeparatesLogicalBlocks) {
+ verifyFormat("class A {\n"
+ "public:\n"
+ " void f();\n"
+ "\n"
+ "private:\n"
+ " void g() {}\n"
+ " // test\n"
+ "protected:\n"
+ " int h;\n"
+ "};",
+ "class A {\n"
+ "public:\n"
+ "void f();\n"
+ "private:\n"
+ "void g() {}\n"
+ "// test\n"
+ "protected:\n"
+ "int h;\n"
+ "};");
+ verifyFormat("class A {\n"
+ "protected:\n"
+ "public:\n"
+ " void f();\n"
+ "};",
+ "class A {\n"
+ "protected:\n"
+ "\n"
+ "public:\n"
+ "\n"
+ " void f();\n"
+ "};");
+
+ // Even ensure proper spacing inside macros.
+ verifyFormat("#define B \\\n"
+ " class A { \\\n"
+ " protected: \\\n"
+ " public: \\\n"
+ " void f(); \\\n"
+ " };",
+ "#define B \\\n"
+ " class A { \\\n"
+ " protected: \\\n"
+ " \\\n"
+ " public: \\\n"
+ " \\\n"
+ " void f(); \\\n"
+ " };",
+ getGoogleStyle());
+ // But don't remove empty lines after macros ending in access specifiers.
+ verifyFormat("#define A private:\n"
+ "\n"
+ "int i;",
+ "#define A private:\n"
+ "\n"
+ "int i;");
+}
+
+TEST_F(FormatTest, FormatsClasses) {
+ verifyFormat("class A : public B {};");
+ verifyFormat("class A : public ::B {};");
+
+ verifyFormat(
+ "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
+ " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
+ verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
+ " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
+ " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
+ verifyFormat(
+ "class A : public B, public C, public D, public E, public F {};");
+ verifyFormat("class AAAAAAAAAAAA : public B,\n"
+ " public C,\n"
+ " public D,\n"
+ " public E,\n"
+ " public F,\n"
+ " public G {};");
+
+ verifyFormat("class\n"
+ " ReallyReallyLongClassName {\n"
+ " int i;\n"
+ "};",
+ getLLVMStyleWithColumns(32));
+ verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
+ " aaaaaaaaaaaaaaaa> {};");
+ verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
+ " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaa> {};");
+ verifyFormat("template <class R, class C>\n"
+ "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
+ " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
+ verifyFormat("class ::A::B {};");
+}
+
+TEST_F(FormatTest, BreakInheritanceStyle) {
+ FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
+ StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
+ FormatStyle::BILS_BeforeComma;
+ verifyFormat("class MyClass : public X {};",
+ StyleWithInheritanceBreakBeforeComma);
+ verifyFormat("class MyClass\n"
+ " : public X\n"
+ " , public Y {};",
+ StyleWithInheritanceBreakBeforeComma);
+ verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
+ " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
+ " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
+ StyleWithInheritanceBreakBeforeComma);
+ verifyFormat("struct aaaaaaaaaaaaa\n"
+ " : public aaaaaaaaaaaaaaaaaaa< // break\n"
+ " aaaaaaaaaaaaaaaa> {};",
+ StyleWithInheritanceBreakBeforeComma);
+
+ FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
+ StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
+ FormatStyle::BILS_AfterColon;
+ verifyFormat("class MyClass : public X {};",
+ StyleWithInheritanceBreakAfterColon);
+ verifyFormat("class MyClass : public X, public Y {};",
+ StyleWithInheritanceBreakAfterColon);
+ verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
+ " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
+ " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
+ StyleWithInheritanceBreakAfterColon);
+ verifyFormat("struct aaaaaaaaaaaaa :\n"
+ " public aaaaaaaaaaaaaaaaaaa< // break\n"
+ " aaaaaaaaaaaaaaaa> {};",
+ StyleWithInheritanceBreakAfterColon);
+
+ FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
+ StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
+ FormatStyle::BILS_AfterComma;
+ verifyFormat("class MyClass : public X {};",
+ StyleWithInheritanceBreakAfterComma);
+ verifyFormat("class MyClass : public X,\n"
+ " public Y {};",
+ StyleWithInheritanceBreakAfterComma);
+ verifyFormat(
+ "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
+ " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
+ "{};",
+ StyleWithInheritanceBreakAfterComma);
+ verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
+ " aaaaaaaaaaaaaaaa> {};",
+ StyleWithInheritanceBreakAfterComma);
+ verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
+ " : public OnceBreak,\n"
+ " public AlwaysBreak,\n"
+ " EvenBasesFitInOneLine {};",
+ StyleWithInheritanceBreakAfterComma);
+}
+
+TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
+ verifyFormat("class A {\n} a, b;");
+ verifyFormat("struct A {\n} a, b;");
+ verifyFormat("union A {\n} a, b;");
+
+ verifyFormat("constexpr class A {\n} a, b;");
+ verifyFormat("constexpr struct A {\n} a, b;");
+ verifyFormat("constexpr union A {\n} a, b;");
+
+ verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
+ verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
+ verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
+
+ verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
+ verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
+ verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
+
+ verifyFormat("namespace ns {\n"
+ "class {\n"
+ "} a, b;\n"
+ "} // namespace ns");
+ verifyFormat("namespace ns {\n"
+ "const class {\n"
+ "} a, b;\n"
+ "} // namespace ns");
+ verifyFormat("namespace ns {\n"
+ "constexpr class C {\n"
+ "} a, b;\n"
+ "} // namespace ns");
+ verifyFormat("namespace ns {\n"
+ "class { /* comment */\n"
+ "} a, b;\n"
+ "} // namespace ns");
+ verifyFormat("namespace ns {\n"
+ "const class { /* comment */\n"
+ "} a, b;\n"
+ "} // namespace ns");
+}
+
+TEST_F(FormatTest, FormatsEnum) {
+ verifyFormat("enum {\n"
+ " Zero,\n"
+ " One = 1,\n"
+ " Two = One + 1,\n"
+ " Three = (One + Two),\n"
+ " Four = (Zero && (One ^ Two)) | (One << Two),\n"
+ " Five = (One, Two, Three, Four, 5)\n"
+ "};");
+ verifyGoogleFormat("enum {\n"
+ " Zero,\n"
+ " One = 1,\n"
+ " Two = One + 1,\n"
+ " Three = (One + Two),\n"
+ " Four = (Zero && (One ^ Two)) | (One << Two),\n"
+ " Five = (One, Two, Three, Four, 5)\n"
+ "};");
+ verifyFormat("enum Enum {};");
+ verifyFormat("enum {};");
+ verifyFormat("enum X E {} d;");
+ verifyFormat("enum __attribute__((...)) E {} d;");
+ verifyFormat("enum __declspec__((...)) E {} d;");
+ verifyFormat("enum [[nodiscard]] E {} d;");
+ verifyFormat("enum {\n"
+ " Bar = Foo<int, int>::value\n"
+ "};",
+ getLLVMStyleWithColumns(30));
+
+ verifyFormat("enum ShortEnum { A, B, C };");
+ verifyGoogleFormat("enum ShortEnum { A, B, C };");
+
+ verifyFormat("enum KeepEmptyLines {\n"
+ " ONE,\n"
+ "\n"
+ " TWO,\n"
+ "\n"
+ " THREE\n"
+ "}",
+ "enum KeepEmptyLines {\n"
+ " ONE,\n"
+ "\n"
+ " TWO,\n"
+ "\n"
+ "\n"
+ " THREE\n"
+ "}");
+ verifyFormat("enum E { // comment\n"
+ " ONE,\n"
+ " TWO\n"
+ "};\n"
+ "int i;");
+
+ FormatStyle EightIndent = getLLVMStyle();
+ EightIndent.IndentWidth = 8;
+ verifyFormat("enum {\n"
+ " VOID,\n"
+ " CHAR,\n"
+ " SHORT,\n"
+ " INT,\n"
+ " LONG,\n"
+ " SIGNED,\n"
+ " UNSIGNED,\n"
+ " BOOL,\n"
+ " FLOAT,\n"
+ " DOUBLE,\n"
+ " COMPLEX\n"
+ "};",
+ EightIndent);
+
+ verifyFormat("enum [[nodiscard]] E {\n"
+ " ONE,\n"
+ " TWO,\n"
+ "};");
+ verifyFormat("enum [[nodiscard]] E {\n"
+ " // Comment 1\n"
+ " ONE,\n"
+ " // Comment 2\n"
+ " TWO,\n"
+ "};");
+ verifyFormat("enum [[clang::enum_extensibility(open)]] E {\n"
+ " // Comment 1\n"
+ " ONE,\n"
+ " // Comment 2\n"
+ " TWO\n"
+ "};");
+ verifyFormat("enum [[nodiscard]] [[clang::enum_extensibility(open)]] E {\n"
+ " // Comment 1\n"
+ " ONE,\n"
+ " // Comment 2\n"
+ " TWO\n"
+ "};");
+ verifyFormat("enum [[clang::enum_extensibility(open)]] E { // foo\n"
+ " A,\n"
+ " // bar\n"
+ " B\n"
+ "};",
+ "enum [[clang::enum_extensibility(open)]] E{// foo\n"
+ " A,\n"
+ " // bar\n"
+ " B};");
+
+ // Not enums.
+ verifyFormat("enum X f() {\n"
+ " a();\n"
+ " return 42;\n"
+ "}");
+ verifyFormat("enum X Type::f() {\n"
+ " a();\n"
+ " return 42;\n"
+ "}");
+ verifyFormat("enum ::X f() {\n"
+ " a();\n"
+ " return 42;\n"
+ "}");
+ verifyFormat("enum ns::X f() {\n"
+ " a();\n"
+ " return 42;\n"
+ "}");
+}
+
+TEST_F(FormatTest, FormatsEnumsWithErrors) {
+ verifyFormat("enum Type {\n"
+ " One = 0; // These semicolons should be commas.\n"
+ " Two = 1;\n"
+ "};");
+ verifyFormat("namespace n {\n"
+ "enum Type {\n"
+ " One,\n"
+ " Two, // missing };\n"
+ " int i;\n"
+ "}\n"
+ "void g() {}");
+}
+
+TEST_F(FormatTest, FormatsEnumStruct) {
+ verifyFormat("enum struct {\n"
+ " Zero,\n"
+ " One = 1,\n"
+ " Two = One + 1,\n"
+ " Three = (One + Two),\n"
+ " Four = (Zero && (One ^ Two)) | (One << Two),\n"
+ " Five = (One, Two, Three, Four, 5)\n"
+ "};");
+ verifyFormat("enum struct Enum {};");
+ verifyFormat("enum struct {};");
+ verifyFormat("enum struct X E {} d;");
+ verifyFormat("enum struct __attribute__((...)) E {} d;");
+ verifyFormat("enum struct __declspec__((...)) E {} d;");
+ verifyFormat("enum struct [[nodiscard]] E {} d;");
+ verifyFormat("enum struct X f() {\n a();\n return 42;\n}");
+
+ verifyFormat("enum struct [[nodiscard]] E {\n"
+ " ONE,\n"
+ " TWO,\n"
+ "};");
+ verifyFormat("enum struct [[nodiscard]] E {\n"
+ " // Comment 1\n"
+ " ONE,\n"
+ " // Comment 2\n"
+ " TWO,\n"
+ "};");
+}
+
+TEST_F(FormatTest, FormatsEnumClass) {
+ verifyFormat("enum class {\n"
+ " Zero,\n"
+ " One = 1,\n"
+ " Two = One + 1,\n"
+ " Three = (One + Two),\n"
+ " Four = (Zero && (One ^ Two)) | (One << Two),\n"
+ " Five = (One, Two, Three, Four, 5)\n"
+ "};");
+ verifyFormat("enum class Enum {};");
+ verifyFormat("enum class {};");
+ verifyFormat("enum class X E {} d;");
+ verifyFormat("enum class __attribute__((...)) E {} d;");
+ verifyFormat("enum class __declspec__((...)) E {} d;");
+ verifyFormat("enum class [[nodiscard]] E {} d;");
+ verifyFormat("enum class X f() {\n a();\n return 42;\n}");
+
+ verifyFormat("enum class [[nodiscard]] E {\n"
+ " ONE,\n"
+ " TWO,\n"
+ "};");
+ verifyFormat("enum class [[nodiscard]] E {\n"
+ " // Comment 1\n"
+ " ONE,\n"
+ " // Comment 2\n"
+ " TWO,\n"
+ "};");
+}
+
+TEST_F(FormatTest, FormatsEnumTypes) {
+ verifyFormat("enum X : int {\n"
+ " A, // Force multiple lines.\n"
+ " B\n"
+ "};");
+ verifyFormat("enum X : int { A, B };");
+ verifyFormat("enum X : std::uint32_t { A, B };");
+}
+
+TEST_F(FormatTest, FormatsTypedefEnum) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ verifyFormat("typedef enum {} EmptyEnum;");
+ verifyFormat("typedef enum { A, B, C } ShortEnum;");
+ verifyFormat("typedef enum {\n"
+ " ZERO = 0,\n"
+ " ONE = 1,\n"
+ " TWO = 2,\n"
+ " THREE = 3\n"
+ "} LongEnum;",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterEnum = true;
+ verifyFormat("typedef enum {} EmptyEnum;");
+ verifyFormat("typedef enum { A, B, C } ShortEnum;");
+ verifyFormat("typedef enum\n"
+ "{\n"
+ " ZERO = 0,\n"
+ " ONE = 1,\n"
+ " TWO = 2,\n"
+ " THREE = 3\n"
+ "} LongEnum;",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsNSEnums) {
+ verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
+ verifyGoogleFormat(
+ "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
+ verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
+ " // Information about someDecentlyLongValue.\n"
+ " someDecentlyLongValue,\n"
+ " // Information about anotherDecentlyLongValue.\n"
+ " anotherDecentlyLongValue,\n"
+ " // Information about aThirdDecentlyLongValue.\n"
+ " aThirdDecentlyLongValue\n"
+ "};");
+ verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
+ " // Information about someDecentlyLongValue.\n"
+ " someDecentlyLongValue,\n"
+ " // Information about anotherDecentlyLongValue.\n"
+ " anotherDecentlyLongValue,\n"
+ " // Information about aThirdDecentlyLongValue.\n"
+ " aThirdDecentlyLongValue\n"
+ "};");
+ verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
+ " a = 1,\n"
+ " b = 2,\n"
+ " c = 3,\n"
+ "};");
+ verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
+ " a = 1,\n"
+ " b = 2,\n"
+ " c = 3,\n"
+ "};");
+ verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
+ " a = 1,\n"
+ " b = 2,\n"
+ " c = 3,\n"
+ "};");
+ verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
+ " a = 1,\n"
+ " b = 2,\n"
+ " c = 3,\n"
+ "};");
+}
+
+TEST_F(FormatTest, FormatsBitfields) {
+ verifyFormat("struct Bitfields {\n"
+ " unsigned sClass : 8;\n"
+ " unsigned ValueKind : 2;\n"
+ "};");
+ verifyFormat("struct A {\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
+ "};");
+ verifyFormat("struct MyStruct {\n"
+ " uchar data;\n"
+ " uchar : 8;\n"
+ " uchar : 8;\n"
+ " uchar other;\n"
+ "};");
+ verifyFormat("struct foo {\n"
+ " uint8_t i_am_a_bit_field_this_long\n"
+ " : struct_with_constexpr::i_am_a_constexpr_lengthhhhh;\n"
+ "};");
+ FormatStyle Style = getLLVMStyle();
+ Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+ verifyFormat("struct Bitfields {\n"
+ " unsigned sClass:8;\n"
+ " unsigned ValueKind:2;\n"
+ " uchar other;\n"
+ "};",
+ Style);
+ verifyFormat("struct A {\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
+ "};",
+ Style);
+ Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+ verifyFormat("struct Bitfields {\n"
+ " unsigned sClass :8;\n"
+ " unsigned ValueKind :2;\n"
+ " uchar other;\n"
+ "};",
+ Style);
+ Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
+ verifyFormat("struct Bitfields {\n"
+ " unsigned sClass: 8;\n"
+ " unsigned ValueKind: 2;\n"
+ " uchar other;\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsNamespaces) {
+ FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
+ LLVMWithNoNamespaceFix.FixNamespaceComments = false;
+
+ verifyFormat("namespace some_namespace {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#define M(x) x##x\n"
+ "namespace M(x) {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#define M(x) x##x\n"
+ "namespace N::inline M(x) {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#define M(x) x##x\n"
+ "namespace M(x)::inline N {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#define M(x) x##x\n"
+ "namespace N::M(x) {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#define M(x) x##x\n"
+ "namespace M::N(x) {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace N::inline D {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace N::inline D::E {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("/* something */ namespace some_namespace {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("namespace {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("/* something */ namespace {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("inline namespace X {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("/* something */ inline namespace X {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("export namespace X {\n"
+ "class A {};\n"
+ "void f() { f(); }\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("using namespace some_namespace;\n"
+ "class A {};\n"
+ "void f() { f(); }",
+ LLVMWithNoNamespaceFix);
+
+ // This code is more common than we thought; if we
+ // layout this correctly the semicolon will go into
+ // its own line, which is undesirable.
+ verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
+ verifyFormat("namespace {\n"
+ "class A {};\n"
+ "};",
+ LLVMWithNoNamespaceFix);
+
+ verifyFormat("namespace {\n"
+ "int SomeVariable = 0; // comment\n"
+ "} // namespace",
+ LLVMWithNoNamespaceFix);
+ verifyFormat("#ifndef HEADER_GUARD\n"
+ "#define HEADER_GUARD\n"
+ "namespace my_namespace {\n"
+ "int i;\n"
+ "} // my_namespace\n"
+ "#endif // HEADER_GUARD",
+ "#ifndef HEADER_GUARD\n"
+ " #define HEADER_GUARD\n"
+ " namespace my_namespace {\n"
+ "int i;\n"
+ "} // my_namespace\n"
+ "#endif // HEADER_GUARD",
+ LLVMWithNoNamespaceFix);
+
+ verifyFormat("namespace A::B {\n"
+ "class C {};\n"
+ "}",
+ LLVMWithNoNamespaceFix);
+
+ FormatStyle Style = getLLVMStyle();
+ Style.NamespaceIndentation = FormatStyle::NI_All;
+ verifyFormat("namespace out {\n"
+ " int i;\n"
+ " namespace in {\n"
+ " int i;\n"
+ " } // namespace in\n"
+ "} // namespace out",
+ "namespace out {\n"
+ "int i;\n"
+ "namespace in {\n"
+ "int i;\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+
+ FormatStyle ShortInlineFunctions = getLLVMStyle();
+ ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
+ ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+ verifyFormat("namespace {\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace { /* comment */\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace { // comment\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " int some_int;\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace interface {\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace interface",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " class X {\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " class X { /* comment */\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " class X { // comment\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " struct X {\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " union X {\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("extern \"C\" {\n"
+ "void f() {\n"
+ " return;\n"
+ "}\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " class X {\n"
+ " void f() { return; }\n"
+ " } x;\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " [[nodiscard]] class X {\n"
+ " void f() { return; }\n"
+ " };\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " static class X {\n"
+ " void f() { return; }\n"
+ " } x;\n"
+ "} // namespace",
+ ShortInlineFunctions);
+ verifyFormat("namespace {\n"
+ " constexpr class X {\n"
+ " void f() { return; }\n"
+ " } x;\n"
+ "} // namespace",
+ ShortInlineFunctions);
+
+ ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
+ verifyFormat("extern \"C\" {\n"
+ " void f() {\n"
+ " return;\n"
+ " }\n"
+ "} // namespace",
+ ShortInlineFunctions);
+
+ Style.NamespaceIndentation = FormatStyle::NI_Inner;
+ verifyFormat("namespace out {\n"
+ "int i;\n"
+ "namespace in {\n"
+ " int i;\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ "namespace out {\n"
+ "int i;\n"
+ "namespace in {\n"
+ "int i;\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+
+ Style.NamespaceIndentation = FormatStyle::NI_None;
+ verifyFormat("template <class T>\n"
+ "concept a_concept = X<>;\n"
+ "namespace B {\n"
+ "struct b_struct {};\n"
+ "} // namespace B",
+ Style);
+ verifyFormat("template <int I>\n"
+ "constexpr void foo()\n"
+ " requires(I == 42)\n"
+ "{}\n"
+ "namespace ns {\n"
+ "void foo() {}\n"
+ "} // namespace ns",
+ Style);
+
+ FormatStyle LLVMWithCompactInnerNamespace = getLLVMStyle();
+ LLVMWithCompactInnerNamespace.CompactNamespaces = true;
+ LLVMWithCompactInnerNamespace.NamespaceIndentation = FormatStyle::NI_Inner;
+ verifyFormat("namespace ns1 { namespace ns2 { namespace ns3 {\n"
+ "// block for debug mode\n"
+ "#ifndef NDEBUG\n"
+ "#endif\n"
+ "}}} // namespace ns1::ns2::ns3",
+ LLVMWithCompactInnerNamespace);
+}
+
+TEST_F(FormatTest, NamespaceMacros) {
+ FormatStyle Style = getLLVMStyle();
+ Style.NamespaceMacros.push_back("TESTSUITE");
+
+ verifyFormat("TESTSUITE(A) {\n"
+ "int foo();\n"
+ "} // TESTSUITE(A)",
+ Style);
+
+ verifyFormat("TESTSUITE(A, B) {\n"
+ "int foo();\n"
+ "} // TESTSUITE(A)",
+ Style);
+
+ // Properly indent according to NamespaceIndentation style
+ Style.NamespaceIndentation = FormatStyle::NI_All;
+ verifyFormat("TESTSUITE(A) {\n"
+ " int foo();\n"
+ "} // TESTSUITE(A)",
+ Style);
+ verifyFormat("TESTSUITE(A) {\n"
+ " namespace B {\n"
+ " int foo();\n"
+ " } // namespace B\n"
+ "} // TESTSUITE(A)",
+ Style);
+ verifyFormat("namespace A {\n"
+ " TESTSUITE(B) {\n"
+ " int foo();\n"
+ " } // TESTSUITE(B)\n"
+ "} // namespace A",
+ Style);
+
+ Style.NamespaceIndentation = FormatStyle::NI_Inner;
+ verifyFormat("TESTSUITE(A) {\n"
+ "TESTSUITE(B) {\n"
+ " int foo();\n"
+ "} // TESTSUITE(B)\n"
+ "} // TESTSUITE(A)",
+ Style);
+ verifyFormat("TESTSUITE(A) {\n"
+ "namespace B {\n"
+ " int foo();\n"
+ "} // namespace B\n"
+ "} // TESTSUITE(A)",
+ Style);
+ verifyFormat("namespace A {\n"
+ "TESTSUITE(B) {\n"
+ " int foo();\n"
+ "} // TESTSUITE(B)\n"
+ "} // namespace A",
+ Style);
+
+ // Properly merge namespace-macros blocks in CompactNamespaces mode
+ Style.NamespaceIndentation = FormatStyle::NI_None;
+ Style.CompactNamespaces = true;
+ verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
+ "}} // TESTSUITE(A::B)",
+ Style);
+
+ verifyFormat("TESTSUITE(out) { TESTSUITE(in) {\n"
+ "}} // TESTSUITE(out::in)",
+ "TESTSUITE(out) {\n"
+ "TESTSUITE(in) {\n"
+ "} // TESTSUITE(in)\n"
+ "} // TESTSUITE(out)",
+ Style);
+
+ verifyFormat("TESTSUITE(out) { TESTSUITE(in) {\n"
+ "}} // TESTSUITE(out::in)",
+ "TESTSUITE(out) {\n"
+ "TESTSUITE(in) {\n"
+ "} // TESTSUITE(in)\n"
+ "} // TESTSUITE(out)",
+ Style);
+
+ // Do not merge different namespaces/macros
+ verifyFormat("namespace out {\n"
+ "TESTSUITE(in) {\n"
+ "} // TESTSUITE(in)\n"
+ "} // namespace out",
+ Style);
+ verifyFormat("TESTSUITE(out) {\n"
+ "namespace in {\n"
+ "} // namespace in\n"
+ "} // TESTSUITE(out)",
+ Style);
+ Style.NamespaceMacros.push_back("FOOBAR");
+ verifyFormat("TESTSUITE(out) {\n"
+ "FOOBAR(in) {\n"
+ "} // FOOBAR(in)\n"
+ "} // TESTSUITE(out)",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsCompactNamespaces) {
+ FormatStyle Style = getLLVMStyle();
+ Style.CompactNamespaces = true;
+ Style.NamespaceMacros.push_back("TESTSUITE");
+
+ verifyFormat("namespace A { namespace B {\n"
+ "}} // namespace A::B",
+ Style);
+
+ verifyFormat("namespace out { namespace in {\n"
+ "}} // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+
+ // Only namespaces which have both consecutive opening and end get compacted
+ verifyFormat("namespace out {\n"
+ "namespace in1 {\n"
+ "} // namespace in1\n"
+ "namespace in2 {\n"
+ "} // namespace in2\n"
+ "} // namespace out",
+ Style);
+
+ verifyFormat("namespace out {\n"
+ "int i;\n"
+ "namespace in {\n"
+ "int j;\n"
+ "} // namespace in\n"
+ "int k;\n"
+ "} // namespace out",
+ "namespace out { int i;\n"
+ "namespace in { int j; } // namespace in\n"
+ "int k; } // namespace out",
+ Style);
+
+ Style.ColumnLimit = 41;
+ verifyFormat("namespace A { namespace B { namespace C {\n"
+ "}}} // namespace A::B::C",
+ "namespace A { namespace B {\n"
+ "namespace C {\n"
+ "}} // namespace B::C\n"
+ "} // namespace A",
+ Style);
+
+ Style.ColumnLimit = 40;
+ verifyFormat("namespace aaaaaaaaaa {\n"
+ "namespace bbbbbbbbbb {\n"
+ "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
+ "namespace aaaaaaaaaa {\n"
+ "namespace bbbbbbbbbb {\n"
+ "} // namespace bbbbbbbbbb\n"
+ "} // namespace aaaaaaaaaa",
+ Style);
+
+ verifyFormat("namespace aaaaaa { namespace bbbbbb {\n"
+ "namespace cccccc {\n"
+ "}}} // namespace aaaaaa::bbbbbb::cccccc",
+ "namespace aaaaaa {\n"
+ "namespace bbbbbb {\n"
+ "namespace cccccc {\n"
+ "} // namespace cccccc\n"
+ "} // namespace bbbbbb\n"
+ "} // namespace aaaaaa",
+ Style);
+
+ verifyFormat("namespace a { namespace b {\n"
+ "namespace c {\n"
+ "}}} // namespace a::b::c",
+ Style);
+
+ Style.ColumnLimit = 80;
+
+ // Extra semicolon after 'inner' closing brace prevents merging
+ verifyFormat("namespace out { namespace in {\n"
+ "}; } // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "}; // namespace in\n"
+ "} // namespace out",
+ Style);
+
+ // Extra semicolon after 'outer' closing brace is conserved
+ verifyFormat("namespace out { namespace in {\n"
+ "}}; // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "} // namespace in\n"
+ "}; // namespace out",
+ Style);
+
+ Style.NamespaceIndentation = FormatStyle::NI_All;
+ verifyFormat("namespace out { namespace in {\n"
+ " int i;\n"
+ "}} // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "int i;\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+ verifyFormat("namespace out { namespace mid {\n"
+ " namespace in {\n"
+ " int j;\n"
+ " } // namespace in\n"
+ " int k;\n"
+ "}} // namespace out::mid",
+ "namespace out { namespace mid {\n"
+ "namespace in { int j; } // namespace in\n"
+ "int k; }} // namespace out::mid",
+ Style);
+
+ verifyFormat("namespace A { namespace B { namespace C {\n"
+ " int i;\n"
+ "}}} // namespace A::B::C\n"
+ "int main() {\n"
+ " if (true)\n"
+ " return 0;\n"
+ "}",
+ "namespace A { namespace B {\n"
+ "namespace C {\n"
+ " int i;\n"
+ "}} // namespace B::C\n"
+ "} // namespace A\n"
+ "int main() {\n"
+ " if (true)\n"
+ " return 0;\n"
+ "}",
+ Style);
+
+ verifyFormat("namespace A { namespace B { namespace C {\n"
+ "#ifdef FOO\n"
+ " int i;\n"
+ "#endif\n"
+ "}}} // namespace A::B::C\n"
+ "int main() {\n"
+ " if (true)\n"
+ " return 0;\n"
+ "}",
+ "namespace A { namespace B {\n"
+ "namespace C {\n"
+ "#ifdef FOO\n"
+ " int i;\n"
+ "#endif\n"
+ "}} // namespace B::C\n"
+ "} // namespace A\n"
+ "int main() {\n"
+ " if (true)\n"
+ " return 0;\n"
+ "}",
+ Style);
+
+ Style.NamespaceIndentation = FormatStyle::NI_Inner;
+ verifyFormat("namespace out { namespace in {\n"
+ " int i;\n"
+ "}} // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "int i;\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+ verifyFormat("namespace out { namespace mid { namespace in {\n"
+ " int i;\n"
+ "}}} // namespace out::mid::in",
+ "namespace out {\n"
+ "namespace mid {\n"
+ "namespace in {\n"
+ "int i;\n"
+ "} // namespace in\n"
+ "} // namespace mid\n"
+ "} // namespace out",
+ Style);
+
+ Style.CompactNamespaces = true;
+ Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeLambdaBody = true;
+ verifyFormat("namespace out { namespace in {\n"
+ "}} // namespace out::in",
+ Style);
+ verifyFormat("namespace out { namespace in {\n"
+ "}} // namespace out::in",
+ "namespace out {\n"
+ "namespace in {\n"
+ "} // namespace in\n"
+ "} // namespace out",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsExternC) {
+ verifyFormat("extern \"C\" {\nint a;");
+ verifyFormat("extern \"C\" {}");
+ verifyFormat("extern \"C\" {\n"
+ "int foo();\n"
+ "}");
+ verifyFormat("extern \"C\" int foo() {}");
+ verifyFormat("extern \"C\" int foo();");
+ verifyFormat("extern \"C\" int foo() {\n"
+ " int i = 42;\n"
+ " return i;\n"
+ "}");
+ verifyFormat(
+ "extern \"C\" char const *const\n"
+ " OpenCL_source_OpenCLRunTime_test_attribute_opencl_unroll_hint;");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ verifyFormat("extern \"C\" int foo() {}", Style);
+ verifyFormat("extern \"C\" int foo();", Style);
+ verifyFormat("extern \"C\" int foo()\n"
+ "{\n"
+ " int i = 42;\n"
+ " return i;\n"
+ "}",
+ Style);
+
+ Style.BraceWrapping.AfterExternBlock = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+ verifyFormat("extern \"C\"\n"
+ "{}",
+ Style);
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ " int foo();\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, IndentExternBlockStyle) {
+ FormatStyle Style = getLLVMStyle();
+ Style.IndentWidth = 2;
+
+ Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+ verifyFormat("extern \"C\" { /*9*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\" {\n"
+ " int foo10();\n"
+ "}",
+ Style);
+
+ Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+ verifyFormat("extern \"C\" { /*11*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\" {\n"
+ "int foo12();\n"
+ "}",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ "int i;\n"
+ "}",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterExternBlock = true;
+ Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+ verifyFormat("extern \"C\"\n"
+ "{ /*13*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\"\n{\n"
+ " int foo14();\n"
+ "}",
+ Style);
+
+ Style.BraceWrapping.AfterExternBlock = false;
+ Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+ verifyFormat("extern \"C\" { /*15*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\" {\n"
+ "int foo16();\n"
+ "}",
+ Style);
+
+ Style.BraceWrapping.AfterExternBlock = true;
+ verifyFormat("extern \"C\"\n"
+ "{ /*13*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ "int foo14();\n"
+ "}",
+ Style);
+
+ Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+ verifyFormat("extern \"C\"\n"
+ "{ /*13*/\n"
+ "}",
+ Style);
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ " int foo14();\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsInlineASM) {
+ verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
+ verifyFormat("asm(\"nop\" ::: \"memory\");");
+ verifyFormat(
+ "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " \"cpuid\\n\\t\"\n"
+ " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
+ " : \"a\"(value));");
+ verifyFormat(
+ "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
+ " __asm {\n"
+ " mov edx,[that] // vtable in edx\n"
+ " mov eax,methodIndex\n"
+ " call [edx][eax*4] // stdcall\n"
+ " }\n"
+ "}",
+ "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
+ " __asm {\n"
+ " mov edx,[that] // vtable in edx\n"
+ " mov eax,methodIndex\n"
+ " call [edx][eax*4] // stdcall\n"
+ " }\n"
+ "}");
+ verifyNoChange("_asm {\n"
+ " xor eax, eax;\n"
+ " cpuid;\n"
+ "}");
+ verifyFormat("void function() {\n"
+ " // comment\n"
+ " asm(\"\");\n"
+ "}");
+ verifyFormat("__asm {\n"
+ "}\n"
+ "int i;",
+ "__asm {\n"
+ "}\n"
+ "int i;");
+
+ auto Style = getLLVMStyleWithColumns(0);
+ constexpr StringRef Code1(
+ "asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
+ constexpr StringRef Code2("asm(\"xyz\"\n"
+ " : \"=a\"(a), \"=d\"(b)\n"
+ " : \"a\"(data));");
+ constexpr StringRef Code3("asm(\"xyz\" : \"=a\"(a), \"=d\"(b)\n"
+ " : \"a\"(data));");
+
+ Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
+ verifyFormat(Code1, Style);
+ verifyNoChange(Code2, Style);
+ verifyNoChange(Code3, Style);
+
+ Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Always;
+ verifyFormat(Code2, Code1, Style);
+ verifyNoChange(Code2, Style);
+ verifyFormat(Code2, Code3, Style);
+}
+
+TEST_F(FormatTest, FormatTryCatch) {
+ verifyFormat("try {\n"
+ " throw a * b;\n"
+ "} catch (int a) {\n"
+ " // Do nothing.\n"
+ "} catch (...) {\n"
+ " exit(42);\n"
+ "}");
+
+ // Function-level try statements.
+ verifyFormat("int f() try { return 4; } catch (...) {\n"
+ " return 5;\n"
+ "}");
+ verifyFormat("class A {\n"
+ " int a;\n"
+ " A() try : a(0) {\n"
+ " } catch (...) {\n"
+ " throw;\n"
+ " }\n"
+ "};");
+ verifyFormat("class A {\n"
+ " int a;\n"
+ " A() try : a(0), b{1} {\n"
+ " } catch (...) {\n"
+ " throw;\n"
+ " }\n"
+ "};");
+ verifyFormat("class A {\n"
+ " int a;\n"
+ " A() try : a(0), b{1}, c{2} {\n"
+ " } catch (...) {\n"
+ " throw;\n"
+ " }\n"
+ "};");
+ verifyFormat("class A {\n"
+ " int a;\n"
+ " A() try : a(0), b{1}, c{2} {\n"
+ " { // New scope.\n"
+ " }\n"
+ " } catch (...) {\n"
+ " throw;\n"
+ " }\n"
+ "};");
+
+ // Incomplete try-catch blocks.
+ verifyIncompleteFormat("try {} catch (");
+}
+
+TEST_F(FormatTest, FormatTryAsAVariable) {
+ auto Style = getLLVMStyle(FormatStyle::LK_C);
+ verifyFormat("int try;", Style);
+ verifyFormat("int try, size;", Style);
+ verifyFormat("try = foo();", Style);
+
+ verifyFormat("if (try < size) {\n return true;\n}");
+
+ verifyFormat("int catch;");
+ verifyFormat("int catch, size;");
+ verifyFormat("catch = foo();");
+ verifyFormat("if (catch < size) {\n return true;\n}");
+
+ Style.Language = FormatStyle::LK_Cpp;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ Style.BraceWrapping.BeforeCatch = true;
+ verifyFormat("try {\n"
+ " int bar = 1;\n"
+ "}\n"
+ "catch (...) {\n"
+ " int bar = 1;\n"
+ "}",
+ Style);
+ verifyFormat("#if NO_EX\n"
+ "try\n"
+ "#endif\n"
+ "{\n"
+ "}\n"
+ "#if NO_EX\n"
+ "catch (...) {\n"
+ "}",
+ Style);
+ verifyFormat("try /* abc */ {\n"
+ " int bar = 1;\n"
+ "}\n"
+ "catch (...) {\n"
+ " int bar = 1;\n"
+ "}",
+ Style);
+ verifyFormat("try\n"
+ "// abc\n"
+ "{\n"
+ " int bar = 1;\n"
+ "}\n"
+ "catch (...) {\n"
+ " int bar = 1;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, FormatSEHTryCatch) {
+ verifyFormat("__try {\n"
+ " int a = b * c;\n"
+ "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
+ " // Do nothing.\n"
+ "}");
+
+ verifyFormat("__try {\n"
+ " int a = b * c;\n"
+ "} __finally {\n"
+ " // Do nothing.\n"
+ "}");
+
+ verifyFormat("DEBUG({\n"
+ " __try {\n"
+ " } __finally {\n"
+ " }\n"
+ "});");
+}
+
+TEST_F(FormatTest, IncompleteTryCatchBlocks) {
+ verifyFormat("try {\n"
+ " f();\n"
+ "} catch {\n"
+ " g();\n"
+ "}");
+ verifyFormat("try {\n"
+ " f();\n"
+ "} catch (A a) MACRO(x) {\n"
+ " g();\n"
+ "} catch (B b) MACRO(x) {\n"
+ " g();\n"
+ "}");
+}
+
+TEST_F(FormatTest, FormatTryCatchBraceStyles) {
+ FormatStyle Style = getLLVMStyle();
+ for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
+ FormatStyle::BS_WebKit}) {
+ Style.BreakBeforeBraces = BraceStyle;
+ verifyFormat("try {\n"
+ " // something\n"
+ "} catch (...) {\n"
+ " // something\n"
+ "}",
+ Style);
+ }
+ Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
+ verifyFormat("try {\n"
+ " // something\n"
+ "}\n"
+ "catch (...) {\n"
+ " // something\n"
+ "}",
+ Style);
+ verifyFormat("__try {\n"
+ " // something\n"
+ "}\n"
+ "__finally {\n"
+ " // something\n"
+ "}",
+ Style);
+ verifyFormat("@try {\n"
+ " // something\n"
+ "}\n"
+ "@finally {\n"
+ " // something\n"
+ "}",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("try\n"
+ "{\n"
+ " // something\n"
+ "}\n"
+ "catch (...)\n"
+ "{\n"
+ " // something\n"
+ "}",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
+ verifyFormat("try\n"
+ " {\n"
+ " // something white\n"
+ " }\n"
+ "catch (...)\n"
+ " {\n"
+ " // something white\n"
+ " }",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_GNU;
+ verifyFormat("try\n"
+ " {\n"
+ " // something\n"
+ " }\n"
+ "catch (...)\n"
+ " {\n"
+ " // something\n"
+ " }",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeCatch = true;
+ verifyFormat("try {\n"
+ " // something\n"
+ "}\n"
+ "catch (...) {\n"
+ " // something\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, StaticInitializers) {
+ verifyFormat("static SomeClass SC = {1, 'a'};");
+
+ verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
+ " 100000000, "
+ "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
+
+ // Here, everything other than the "}" would fit on a line.
+ verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
+ " 10000000000000000000000000};");
+ verifyFormat("S s = {a,\n"
+ "\n"
+ " b};",
+ "S s = {\n"
+ " a,\n"
+ "\n"
+ " b\n"
+ "};");
+
+ // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
+ // line. However, the formatting looks a bit off and this probably doesn't
+ // happen often in practice.
+ verifyFormat("static int Variable[1] = {\n"
+ " {1000000000000000000000000000000000000}};",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, DesignatedInitializers) {
+ verifyFormat("const struct A a = {.a = 1, .b = 2};");
+ verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
+ " .bbbbbbbbbb = 2,\n"
+ " .cccccccccc = 3,\n"
+ " .dddddddddd = 4,\n"
+ " .eeeeeeeeee = 5};");
+ verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
+ " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
+ " .ccccccccccccccccccccccccccc = 3,\n"
+ " .ddddddddddddddddddddddddddd = 4,\n"
+ " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
+
+ verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
+
+ verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
+ verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
+ " [2] = bbbbbbbbbb,\n"
+ " [3] = cccccccccc,\n"
+ " [4] = dddddddddd,\n"
+ " [5] = eeeeeeeeee};");
+ verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
+ " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " [3] = cccccccccccccccccccccccccccccccccccccc,\n"
+ " [4] = dddddddddddddddddddddddddddddddddddddd,\n"
+ " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
+
+ verifyFormat("for (const TestCase &test_case : {\n"
+ " TestCase{\n"
+ " .a = 1,\n"
+ " .b = 1,\n"
+ " },\n"
+ " TestCase{\n"
+ " .a = 2,\n"
+ " .b = 2,\n"
+ " },\n"
+ " }) {\n"
+ "}");
+}
+
+TEST_F(FormatTest, BracedInitializerIndentWidth) {
+ auto Style = getLLVMStyleWithColumns(60);
+ Style.BinPackArguments = true;
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BreakAfterOpenBracketBracedList = true;
+ Style.BracedInitializerIndentWidth = 6;
+
+ // Non-initializing braces are unaffected by BracedInitializerIndentWidth.
+ verifyFormat("enum class {\n"
+ " One,\n"
+ " Two,\n"
+ "};",
+ Style);
+ verifyFormat("class Foo {\n"
+ " Foo() {}\n"
+ " void bar();\n"
+ "};",
+ Style);
+ verifyFormat("void foo() {\n"
+ " auto bar = baz;\n"
+ " return baz;\n"
+ "};",
+ Style);
+ verifyFormat("auto foo = [&] {\n"
+ " auto bar = baz;\n"
+ " return baz;\n"
+ "};",
+ Style);
+ verifyFormat("{\n"
+ " auto bar = baz;\n"
+ " return baz;\n"
+ "};",
+ Style);
+ // Non-brace initialization is unaffected by BracedInitializerIndentWidth.
+ verifyFormat("SomeClass clazz(\n"
+ " \"xxxxxxxxxxxxxxxxxx\", \"yyyyyyyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzzzzzzz\");",
+ Style);
+
+ // The following types of initialization are all affected by
+ // BracedInitializerIndentWidth. Aggregate initialization.
+ verifyFormat("int LooooooooooooooooooooooooongVariable[2] = {\n"
+ " 10000000, 20000000};",
+ Style);
+ verifyFormat("SomeStruct s{\n"
+ " \"xxxxxxxxxxxxxxxx\", \"yyyyyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzzzzz\"};",
+ Style);
+ // Designated initializers.
+ verifyFormat("int LooooooooooooooooooooooooongVariable[2] = {\n"
+ " [0] = 10000000, [1] = 20000000};",
+ Style);
+ verifyFormat("SomeStruct s{\n"
+ " .foo = \"xxxxxxxxxxxxx\",\n"
+ " .bar = \"yyyyyyyyyyyyy\",\n"
+ " .baz = \"zzzzzzzzzzzzz\"};",
+ Style);
+ // List initialization.
+ verifyFormat("SomeStruct s{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ verifyFormat("SomeStruct{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ verifyFormat("new SomeStruct{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Member initializer.
+ verifyFormat("class SomeClass {\n"
+ " SomeStruct s{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ " };\n"
+ "};",
+ Style);
+ // Constructor member initializer.
+ verifyFormat("SomeClass::SomeClass : strct{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ " } {}",
+ Style);
+ // Copy initialization.
+ verifyFormat("SomeStruct s = SomeStruct{\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Copy list initialization.
+ verifyFormat("SomeStruct s = {\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Assignment operand initialization.
+ verifyFormat("s = {\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Returned object initialization.
+ verifyFormat("return {\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Initializer list.
+ verifyFormat("auto initializerList = {\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "};",
+ Style);
+ // Function parameter initialization.
+ verifyFormat("func({\n"
+ " \"xxxxxxxxxxxxx\",\n"
+ " \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\",\n"
+ "});",
+ Style);
+ // Nested init lists.
+ verifyFormat("SomeStruct s = {\n"
+ " {{init1, init2, init3, init4, init5},\n"
+ " {init1, init2, init3, init4, init5}}};",
+ Style);
+ verifyFormat("SomeStruct s = {\n"
+ " {{\n"
+ " .init1 = 1,\n"
+ " .init2 = 2,\n"
+ " .init3 = 3,\n"
+ " .init4 = 4,\n"
+ " .init5 = 5,\n"
+ " },\n"
+ " {init1, init2, init3, init4, init5}}};",
+ Style);
+ verifyFormat("SomeArrayT a[3] = {\n"
+ " {\n"
+ " foo,\n"
+ " bar,\n"
+ " },\n"
+ " {\n"
+ " foo,\n"
+ " bar,\n"
+ " },\n"
+ " SomeArrayT{},\n"
+ "};",
+ Style);
+ verifyFormat("SomeArrayT a[3] = {\n"
+ " {foo},\n"
+ " {\n"
+ " {\n"
+ " init1,\n"
+ " init2,\n"
+ " init3,\n"
+ " },\n"
+ " {\n"
+ " init1,\n"
+ " init2,\n"
+ " init3,\n"
+ " },\n"
+ " },\n"
+ " {baz},\n"
+ "};",
+ Style);
+
+ // Aligning after open braces unaffected by BracedInitializerIndentWidth.
+ Style.AlignAfterOpenBracket = true;
+ Style.BreakAfterOpenBracketBracedList = false;
+ verifyFormat("SomeStruct s{\"xxxxxxxxxxxxx\", \"yyyyyyyyyyyyy\",\n"
+ " \"zzzzzzzzzzzzz\"};",
+ Style);
+}
+
+TEST_F(FormatTest, NestedStaticInitializers) {
+ verifyFormat("static A x = {{{}}};");
+ verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
+ " {init1, init2, init3, init4}}};",
+ getLLVMStyleWithColumns(50));
+
+ verifyFormat("somes Status::global_reps[3] = {\n"
+ " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
+ " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
+ " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
+ getLLVMStyleWithColumns(60));
+ verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
+ " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
+ " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
+ " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
+ verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
+ " {rect.fRight - rect.fLeft, rect.fBottom - "
+ "rect.fTop}};");
+
+ verifyFormat(
+ "SomeArrayOfSomeType a = {\n"
+ " {{1, 2, 3},\n"
+ " {1, 2, 3},\n"
+ " {111111111111111111111111111111, 222222222222222222222222222222,\n"
+ " 333333333333333333333333333333},\n"
+ " {1, 2, 3},\n"
+ " {1, 2, 3}}};");
+ verifyFormat(
+ "SomeArrayOfSomeType a = {\n"
+ " {{1, 2, 3}},\n"
+ " {{1, 2, 3}},\n"
+ " {{111111111111111111111111111111, 222222222222222222222222222222,\n"
+ " 333333333333333333333333333333}},\n"
+ " {{1, 2, 3}},\n"
+ " {{1, 2, 3}}};");
+
+ verifyFormat("struct {\n"
+ " unsigned bit;\n"
+ " const char *const name;\n"
+ "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
+ " {kOsWin, \"Windows\"},\n"
+ " {kOsLinux, \"Linux\"},\n"
+ " {kOsCrOS, \"Chrome OS\"}};");
+ verifyFormat("struct {\n"
+ " unsigned bit;\n"
+ " const char *const name;\n"
+ "} kBitsToOs[] = {\n"
+ " {kOsMac, \"Mac\"},\n"
+ " {kOsWin, \"Windows\"},\n"
+ " {kOsLinux, \"Linux\"},\n"
+ " {kOsCrOS, \"Chrome OS\"},\n"
+ "};");
+}
+
+TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
+ verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
+ " \\\n"
+ " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
+}
+
+TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
+ verifyFormat("virtual void write(ELFWriter *writerrr,\n"
+ " OwningPtr<FileOutputBuffer> &buffer) = 0;");
+
+ // Do break defaulted and deleted functions.
+ verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
+ " default;",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
+ " delete;",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
+ verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("#define Q \\\n"
+ " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n"
+ " \"aaaaaaaa.cpp\"",
+ "#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, UnderstandsLinePPDirective) {
+ verifyFormat("# 123 \"A string literal\"",
+ " # 123 \"A string literal\"");
+}
+
+TEST_F(FormatTest, LayoutUnknownPPDirective) {
+ verifyFormat("#;");
+ verifyFormat("#\n;\n;\n;");
+}
+
+TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
+ verifyFormat("#line 42 \"test\"", "# \\\n line \\\n 42 \\\n \"test\"");
+ verifyFormat("#define A B", "# \\\n define \\\n A \\\n B",
+ getLLVMStyleWithColumns(12));
+}
+
+TEST_F(FormatTest, EndOfFileEndsPPDirective) {
+ verifyFormat("#line 42 \"test\"", "# \\\n line \\\n 42 \\\n \"test\"");
+ verifyFormat("#define A B", "# \\\n define \\\n A \\\n B");
+}
+
+TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
+ verifyFormat("#define A \\x20");
+ verifyFormat("#define A \\ x20");
+ verifyFormat("#define A \\ x20", "#define A \\ x20");
+ verifyFormat("#define A ''");
+ verifyFormat("#define A ''qqq");
+ verifyFormat("#define A `qqq");
+ verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
+ verifyFormat("const char *c = STRINGIFY(\n"
+ "\\na : b);",
+ "const char * c = STRINGIFY(\n"
+ "\\na : b);");
+
+ verifyFormat("a\r\\");
+ verifyFormat("a\v\\");
+ verifyFormat("a\f\\");
+}
+
+TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
+ FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
+ style.IndentWidth = 4;
+ style.PPIndentWidth = 1;
+
+ style.IndentPPDirectives = FormatStyle::PPDIS_None;
+ verifyFormat("#ifdef __linux__\n"
+ "void foo() {\n"
+ " int x = 0;\n"
+ "}\n"
+ "#define FOO\n"
+ "#endif\n"
+ "void bar() {\n"
+ " int y = 0;\n"
+ "}",
+ style);
+
+ style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+ verifyFormat("#ifdef __linux__\n"
+ "void foo() {\n"
+ " int x = 0;\n"
+ "}\n"
+ "# define FOO foo\n"
+ "#endif\n"
+ "void bar() {\n"
+ " int y = 0;\n"
+ "}",
+ style);
+
+ style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
+ verifyFormat("#ifdef __linux__\n"
+ "void foo() {\n"
+ " int x = 0;\n"
+ "}\n"
+ " #define FOO foo\n"
+ "#endif\n"
+ "void bar() {\n"
+ " int y = 0;\n"
+ "}",
+ style);
+ verifyFormat("#if 1\n"
+ " // some comments\n"
+ " // another\n"
+ " #define foo 1\n"
+ "// not a define comment\n"
+ "void bar() {\n"
+ " // comment\n"
+ " int y = 0;\n"
+ "}",
+ "#if 1\n"
+ "// some comments\n"
+ "// another\n"
+ "#define foo 1\n"
+ "// not a define comment\n"
+ "void bar() {\n"
+ " // comment\n"
+ " int y = 0;\n"
+ "}",
+ style);
+
+ style.IndentPPDirectives = FormatStyle::PPDIS_None;
+ verifyFormat("#ifdef foo\n"
+ "#define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+ verifyFormat("if (emacs) {\n"
+ "#ifdef is\n"
+ "#define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}",
+ style);
+ verifyFormat("#if abc\n"
+ "#ifdef foo\n"
+ "#define bar() \\\n"
+ " if (A) { \\\n"
+ " if (B) { \\\n"
+ " C(); \\\n"
+ " } \\\n"
+ " } \\\n"
+ " D();\n"
+ "#endif\n"
+ "#endif",
+ style);
+ verifyFormat("#ifndef foo\n"
+ "#define foo\n"
+ "if (emacs) {\n"
+ "#ifdef is\n"
+ "#define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}\n"
+ "#endif",
+ style);
+ verifyFormat("#if 1\n"
+ "#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }\n"
+ "#endif",
+ style);
+ verifyFormat("#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }",
+ style);
+
+ style.PPIndentWidth = 2;
+ verifyFormat("#ifdef foo\n"
+ "#define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+ style.IndentWidth = 8;
+ verifyFormat("#ifdef foo\n"
+ "#define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+
+ style.IndentWidth = 1;
+ style.PPIndentWidth = 4;
+ verifyFormat("#if 1\n"
+ "#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }\n"
+ "#endif",
+ style);
+ verifyFormat("#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }",
+ style);
+
+ style.IndentPPDirectives = FormatStyle::PPDIS_Leave;
+ style.IndentWidth = 4;
+ verifyNoChange("#ifndef foo\n"
+ "#define foo\n"
+ "if (emacs) {\n"
+ "#ifdef is\n"
+ "#define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}\n"
+ "#endif",
+ style);
+ verifyNoChange("#ifndef foo\n"
+ " #define foo\n"
+ "if (emacs) {\n"
+ " #ifdef is\n"
+ "#define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ " #endif\n"
+ "}\n"
+ "#endif",
+ style);
+ verifyNoChange(" #ifndef foo\n"
+ "# define foo\n"
+ "if (emacs) {\n"
+ "#ifdef is\n"
+ " # define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}\n"
+ " #endif",
+ style);
+ verifyNoChange("#ifdef foo\n"
+ "#else\n"
+ "/* This is a comment */\n"
+ "#ifdef BAR\n"
+ "#endif\n"
+ "#endif",
+ style);
+
+ style.IndentWidth = 1;
+ style.PPIndentWidth = 4;
+ verifyNoChange("# if 1\n"
+ " #define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }\n"
+ "# endif",
+ style);
+
+ style.IndentWidth = 4;
+ style.PPIndentWidth = 1;
+ style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+ verifyFormat("#ifdef foo\n"
+ "# define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+ verifyFormat("#if abc\n"
+ "# ifdef foo\n"
+ "# define bar() \\\n"
+ " if (A) { \\\n"
+ " if (B) { \\\n"
+ " C(); \\\n"
+ " } \\\n"
+ " } \\\n"
+ " D();\n"
+ "# endif\n"
+ "#endif",
+ style);
+ verifyFormat("#ifndef foo\n"
+ "#define foo\n"
+ "if (emacs) {\n"
+ "#ifdef is\n"
+ "# define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}\n"
+ "#endif",
+ style);
+ verifyFormat("#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }",
+ style);
+
+ style.PPIndentWidth = 2;
+ style.IndentWidth = 8;
+ verifyFormat("#ifdef foo\n"
+ "# define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+
+ style.PPIndentWidth = 4;
+ style.IndentWidth = 1;
+ verifyFormat("#define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }",
+ style);
+
+ style.IndentWidth = 4;
+ style.PPIndentWidth = 1;
+ style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
+ verifyFormat("if (emacs) {\n"
+ "#ifdef is\n"
+ " #define lit \\\n"
+ " if (af) { \\\n"
+ " return duh(); \\\n"
+ " }\n"
+ "#endif\n"
+ "}",
+ style);
+ verifyFormat("#if abc\n"
+ " #ifdef foo\n"
+ " #define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ " #endif\n"
+ "#endif",
+ style);
+ verifyFormat("#if 1\n"
+ " #define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }\n"
+ "#endif",
+ style);
+
+ style.PPIndentWidth = 2;
+ verifyFormat("#ifdef foo\n"
+ " #define bar() \\\n"
+ " if (A) { \\\n"
+ " B(); \\\n"
+ " } \\\n"
+ " C();\n"
+ "#endif",
+ style);
+
+ style.PPIndentWidth = 4;
+ style.IndentWidth = 1;
+ verifyFormat("#if 1\n"
+ " #define X \\\n"
+ " { \\\n"
+ " x; \\\n"
+ " x; \\\n"
+ " }\n"
+ "#endif",
+ style);
+}
+
+TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
+ verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
+ verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12));
+ verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12));
+ // FIXME: We never break before the macro name.
+ verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12));
+
+ verifyFormat("#define A A\n#define A A");
+ verifyFormat("#define A(X) A\n#define A A");
+
+ verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
+ verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22));
+}
+
+TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
+ verifyFormat("// somecomment\n"
+ "#include \"a.h\"\n"
+ "#define A( \\\n"
+ " A, B)\n"
+ "#include \"b.h\"\n"
+ "// somecomment",
+ " // somecomment\n"
+ " #include \"a.h\"\n"
+ "#define A(A,\\\n"
+ " B)\n"
+ " #include \"b.h\"\n"
+ " // somecomment",
+ getLLVMStyleWithColumns(13));
+}
+
+TEST_F(FormatTest, LayoutSingleHash) { verifyFormat("#\na;"); }
+
+TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
+ verifyFormat("#define A \\\n"
+ " c; \\\n"
+ " e;\n"
+ "f;",
+ "#define A c; e;\n"
+ "f;",
+ getLLVMStyleWithColumns(14));
+}
+
+TEST_F(FormatTest, LayoutRemainingTokens) {
+ verifyFormat("{\n"
+ "}");
+}
+
+TEST_F(FormatTest, MacroDefinitionInsideStatement) {
+ verifyFormat("int x,\n"
+ "#define A\n"
+ " y;",
+ "int x,\n#define A\ny;");
+}
+
+TEST_F(FormatTest, HashInMacroDefinition) {
+ verifyFormat("#define A(c) L#c");
+ verifyFormat("#define A(c) u#c");
+ verifyFormat("#define A(c) U#c");
+ verifyFormat("#define A(c) u8#c");
+ verifyFormat("#define A(c) LR#c");
+ verifyFormat("#define A(c) uR#c");
+ verifyFormat("#define A(c) UR#c");
+ verifyFormat("#define A(c) u8R#c");
+ verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11));
+ verifyFormat("#define A \\\n"
+ " { \\\n"
+ " f(#c); \\\n"
+ " }",
+ getLLVMStyleWithColumns(11));
+
+ verifyFormat("#define A(X) \\\n"
+ " void function##X()",
+ getLLVMStyleWithColumns(22));
+
+ verifyFormat("#define A(a, b, c) \\\n"
+ " void a##b##c()",
+ getLLVMStyleWithColumns(22));
+
+ verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
+
+ verifyFormat("{\n"
+ " {\n"
+ "#define GEN_ID(_x) char *_x{#_x}\n"
+ " GEN_ID(one);\n"
+ " }\n"
+ "}");
+}
+
+TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
+ verifyFormat("#define A (x)");
+ verifyFormat("#define A(x)");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
+ verifyFormat("#define true ((foo)1)", Style);
+ Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+ verifyFormat("#define false((foo)0)", Style);
+}
+
+TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
+ verifyFormat("#define A b;",
+ "#define A \\\n"
+ " \\\n"
+ " b;",
+ getLLVMStyleWithColumns(25));
+ verifyNoChange("#define A \\\n"
+ " \\\n"
+ " a; \\\n"
+ " b;",
+ getLLVMStyleWithColumns(11));
+ verifyNoChange("#define A \\\n"
+ " a; \\\n"
+ " \\\n"
+ " b;",
+ getLLVMStyleWithColumns(11));
+}
+
+TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
+ verifyIncompleteFormat("#define A :");
+ verifyFormat("#define SOMECASES \\\n"
+ " case 1: \\\n"
+ " case 2",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("#define MACRO(a) \\\n"
+ " if (a) \\\n"
+ " f(); \\\n"
+ " else \\\n"
+ " g()",
+ getLLVMStyleWithColumns(18));
+ verifyFormat("#define A template <typename T>");
+ verifyIncompleteFormat("#define STR(x) #x\n"
+ "f(STR(this_is_a_string_literal{));");
+ verifyFormat("#pragma omp threadprivate( \\\n"
+ " y)), // expected-warning",
+ getLLVMStyleWithColumns(28));
+ verifyFormat("#d, = };");
+ verifyFormat("#if \"a");
+ verifyIncompleteFormat("({\n"
+ "#define b \\\n"
+ " } \\\n"
+ " a\n"
+ "a",
+ getLLVMStyleWithColumns(15));
+ verifyFormat("#define A \\\n"
+ " { \\\n"
+ " {\n"
+ "#define B \\\n"
+ " } \\\n"
+ " }",
+ getLLVMStyleWithColumns(15));
+ verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
+ verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
+ verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
+ verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}");
+ verifyNoCrash("#else\n"
+ "#else\n"
+ "#endif\n"
+ "#endif");
+ verifyNoCrash("#else\n"
+ "#if X\n"
+ "#endif\n"
+ "#endif");
+ verifyNoCrash("#else\n"
+ "#endif\n"
+ "#if X\n"
+ "#endif");
+ verifyNoCrash("#if X\n"
+ "#else\n"
+ "#else\n"
+ "#endif\n"
+ "#endif");
+ verifyNoCrash("#if X\n"
+ "#elif Y\n"
+ "#elif Y\n"
+ "#endif\n"
+ "#endif");
+ verifyNoCrash("#endif\n"
+ "#endif");
+ verifyNoCrash("#endif\n"
+ "#else");
+ verifyNoCrash("#endif\n"
+ "#elif Y");
+}
+
+TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
+ verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
+ verifyFormat("class A : public QObject {\n"
+ " Q_OBJECT\n"
+ "\n"
+ " A() {}\n"
+ "};",
+ "class A : public QObject {\n"
+ " Q_OBJECT\n"
+ "\n"
+ " A() {\n}\n"
+ "} ;");
+ verifyFormat("MACRO\n"
+ "/*static*/ int i;",
+ "MACRO\n"
+ " /*static*/ int i;");
+ verifyFormat("SOME_MACRO\n"
+ "namespace {\n"
+ "void f();\n"
+ "} // namespace",
+ "SOME_MACRO\n"
+ " namespace {\n"
+ "void f( );\n"
+ "} // namespace");
+ // Only if the identifier contains at least 5 characters.
+ verifyFormat("HTTP f();", "HTTP\nf();");
+ verifyNoChange("MACRO\nf();");
+ // Only if everything is upper case.
+ verifyFormat("class A : public QObject {\n"
+ " Q_Object A() {}\n"
+ "};",
+ "class A : public QObject {\n"
+ " Q_Object\n"
+ " A() {\n}\n"
+ "} ;");
+
+ // Only if the next line can actually start an unwrapped line.
+ verifyFormat("SOME_WEIRD_LOG_MACRO << SomeThing;", "SOME_WEIRD_LOG_MACRO\n"
+ "<< SomeThing;");
+
+ verifyFormat("GGGG(ffff(xxxxxxxxxxxxxxxxxxxx)->yyyyyyyyyyyyyyyyyyyy)(foo);",
+ "GGGG(ffff(xxxxxxxxxxxxxxxxxxxx)->yyyyyyyyyyyyyyyyyyyy)\n"
+ "(foo);",
+ getLLVMStyleWithColumns(60));
+
+ verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
+ "(n, buffers))",
+ getChromiumStyle(FormatStyle::LK_Cpp));
+
+ // See PR41483
+ verifyNoChange("/**/ FOO(a)\n"
+ "FOO(b)");
+}
+
+TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
+ verifyFormat("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
+ "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
+ "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
+ "class X {};\n"
+ "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
+ "int *createScopDetectionPass() { return 0; }",
+ " INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
+ " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
+ " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
+ " class X {};\n"
+ " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
+ " int *createScopDetectionPass() { return 0; }");
+ // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
+ // braces, so that inner block is indented one level more.
+ verifyFormat("int q() {\n"
+ " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
+ " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
+ " IPC_END_MESSAGE_MAP()\n"
+ "}",
+ "int q() {\n"
+ " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
+ " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
+ " IPC_END_MESSAGE_MAP()\n"
+ "}");
+
+ // Same inside macros.
+ verifyFormat("#define LIST(L) \\\n"
+ " L(A) \\\n"
+ " L(B) \\\n"
+ " L(C)",
+ "#define LIST(L) \\\n"
+ " L(A) \\\n"
+ " L(B) \\\n"
+ " L(C)",
+ getGoogleStyle());
+
+ // These must not be recognized as macros.
+ verifyFormat("int q() {\n"
+ " f(x);\n"
+ " f(x) {}\n"
+ " f(x)->g();\n"
+ " f(x)->*g();\n"
+ " f(x).g();\n"
+ " f(x) = x;\n"
+ " f(x) += x;\n"
+ " f(x) -= x;\n"
+ " f(x) *= x;\n"
+ " f(x) /= x;\n"
+ " f(x) %= x;\n"
+ " f(x) &= x;\n"
+ " f(x) |= x;\n"
+ " f(x) ^= x;\n"
+ " f(x) >>= x;\n"
+ " f(x) <<= x;\n"
+ " f(x)[y].z();\n"
+ " LOG(INFO) << x;\n"
+ " ifstream(x) >> x;\n"
+ "}",
+ "int q() {\n"
+ " f(x)\n;\n"
+ " f(x)\n {}\n"
+ " f(x)\n->g();\n"
+ " f(x)\n->*g();\n"
+ " f(x)\n.g();\n"
+ " f(x)\n = x;\n"
+ " f(x)\n += x;\n"
+ " f(x)\n -= x;\n"
+ " f(x)\n *= x;\n"
+ " f(x)\n /= x;\n"
+ " f(x)\n %= x;\n"
+ " f(x)\n &= x;\n"
+ " f(x)\n |= x;\n"
+ " f(x)\n ^= x;\n"
+ " f(x)\n >>= x;\n"
+ " f(x)\n <<= x;\n"
+ " f(x)\n[y].z();\n"
+ " LOG(INFO)\n << x;\n"
+ " ifstream(x)\n >> x;\n"
+ "}");
+ verifyFormat("int q() {\n"
+ " F(x)\n"
+ " if (1) {\n"
+ " }\n"
+ " F(x)\n"
+ " while (1) {\n"
+ " }\n"
+ " F(x)\n"
+ " G(x);\n"
+ " F(x)\n"
+ " try {\n"
+ " Q();\n"
+ " } catch (...) {\n"
+ " }\n"
+ "}",
+ "int q() {\n"
+ "F(x)\n"
+ "if (1) {}\n"
+ "F(x)\n"
+ "while (1) {}\n"
+ "F(x)\n"
+ "G(x);\n"
+ "F(x)\n"
+ "try { Q(); } catch (...) {}\n"
+ "}");
+ verifyFormat("class A {\n"
+ " A() : t(0) {}\n"
+ " A(int i) noexcept() : {}\n"
+ " A(X x)\n" // FIXME: function-level try blocks are broken.
+ " try : t(0) {\n"
+ " } catch (...) {\n"
+ " }\n"
+ "};",
+ "class A {\n"
+ " A()\n : t(0) {}\n"
+ " A(int i)\n noexcept() : {}\n"
+ " A(X x)\n"
+ " try : t(0) {} catch (...) {}\n"
+ "};");
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ Style.BraceWrapping.AfterFunction = true;
+ verifyFormat("void f()\n"
+ "try\n"
+ "{\n"
+ "}",
+ "void f() try {\n"
+ "}",
+ Style);
+ verifyFormat("class SomeClass {\n"
+ "public:\n"
+ " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
+ "};",
+ "class SomeClass {\n"
+ "public:\n"
+ " SomeClass()\n"
+ " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
+ "};");
+ verifyFormat("class SomeClass {\n"
+ "public:\n"
+ " SomeClass()\n"
+ " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
+ "};",
+ "class SomeClass {\n"
+ "public:\n"
+ " SomeClass()\n"
+ " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
+ "};",
+ getLLVMStyleWithColumns(40));
+
+ verifyFormat("MACRO(>)");
+
+ // Some macros contain an implicit semicolon.
+ Style = getLLVMStyle();
+ Style.StatementMacros.push_back("FOO");
+ verifyFormat("FOO(a) int b = 0;");
+ verifyFormat("FOO(a)\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("FOO(a);\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("FOO()\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("FOO\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("void f() {\n"
+ " FOO(a)\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("FOO(a)\n"
+ "FOO(b)",
+ Style);
+ verifyFormat("int a = 0;\n"
+ "FOO(b)\n"
+ "int c = 0;",
+ Style);
+ verifyFormat("int a = 0;\n"
+ "int x = FOO(a)\n"
+ "int b = 0;",
+ Style);
+ verifyFormat("void foo(int a) { FOO(a) }\n"
+ "uint32_t bar() {}",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
+ FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
+
+ verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
+ ZeroColumn);
+}
+
+TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
+ verifyFormat("#define A \\\n"
+ " f({ \\\n"
+ " g(); \\\n"
+ " });",
+ getLLVMStyleWithColumns(11));
+}
+
+TEST_F(FormatTest, IndentPreprocessorDirectives) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ Style.IndentPPDirectives = FormatStyle::PPDIS_None;
+ verifyFormat("#ifdef _WIN32\n"
+ "#define A 0\n"
+ "#ifdef VAR2\n"
+ "#define B 1\n"
+ "#include <someheader.h>\n"
+ "#define MACRO \\\n"
+ " some_very_long_func_aaaaaaaaaa();\n"
+ "#endif\n"
+ "#else\n"
+ "#define A 1\n"
+ "#endif",
+ Style);
+ Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+ verifyFormat("#if 1\n"
+ "# define __STR(x) #x\n"
+ "#endif",
+ Style);
+ verifyFormat("#ifdef _WIN32\n"
+ "# define A 0\n"
+ "# ifdef VAR2\n"
+ "# define B 1\n"
+ "# include <someheader.h>\n"
+ "# define MACRO \\\n"
+ " some_very_long_func_aaaaaaaaaa();\n"
+ "# endif\n"
+ "#else\n"
+ "# define A 1\n"
+ "#endif",
+ Style);
+ verifyFormat("#if A\n"
+ "# define MACRO \\\n"
+ " void a(int x) { \\\n"
+ " b(); \\\n"
+ " c(); \\\n"
+ " d(); \\\n"
+ " e(); \\\n"
+ " f(); \\\n"
+ " }\n"
+ "#endif",
+ Style);
+ // Comments before include guard.
+ verifyFormat("// file comment\n"
+ "// file comment\n"
+ "#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // Test with include guards.
+ verifyFormat("#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // Include guards must have a #define with the same variable immediately
+ // after #ifndef.
+ verifyFormat("#ifndef NOT_GUARD\n"
+ "# define FOO\n"
+ "code();\n"
+ "#endif",
+ Style);
+
+ // Include guards must cover the entire file.
+ verifyFormat("code();\n"
+ "code();\n"
+ "#ifndef NOT_GUARD\n"
+ "# define NOT_GUARD\n"
+ "code();\n"
+ "#endif",
+ Style);
+ verifyFormat("#ifndef NOT_GUARD\n"
+ "# define NOT_GUARD\n"
+ "code();\n"
+ "#endif\n"
+ "code();",
+ Style);
+ // Test with trailing blank lines.
+ verifyFormat("#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // Include guards don't have #else.
+ verifyFormat("#ifndef NOT_GUARD\n"
+ "# define NOT_GUARD\n"
+ "code();\n"
+ "#else\n"
+ "#endif",
+ Style);
+ verifyFormat("#ifndef NOT_GUARD\n"
+ "# define NOT_GUARD\n"
+ "code();\n"
+ "#elif FOO\n"
+ "#endif",
+ Style);
+ // Non-identifier #define after potential include guard.
+ verifyFormat("#ifndef FOO\n"
+ "# define 1\n"
+ "#endif",
+ Style);
+ // #if closes past last non-preprocessor line.
+ verifyFormat("#ifndef FOO\n"
+ "#define FOO\n"
+ "#if 1\n"
+ "int i;\n"
+ "# define A 0\n"
+ "#endif\n"
+ "#endif",
+ Style);
+ // Don't crash if there is an #elif directive without a condition.
+ verifyFormat("#if 1\n"
+ "int x;\n"
+ "#elif\n"
+ "int y;\n"
+ "#else\n"
+ "int z;\n"
+ "#endif",
+ Style);
+ // FIXME: This doesn't handle the case where there's code between the
+ // #ifndef and #define but all other conditions hold. This is because when
+ // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
+ // previous code line yet, so we can't detect it.
+ verifyFormat("#ifndef NOT_GUARD\n"
+ "code();\n"
+ "#define NOT_GUARD\n"
+ "code();\n"
+ "#endif",
+ "#ifndef NOT_GUARD\n"
+ "code();\n"
+ "# define NOT_GUARD\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // FIXME: This doesn't handle cases where legitimate preprocessor lines may
+ // be outside an include guard. Examples are #pragma once and
+ // #pragma GCC diagnostic, or anything else that does not change the meaning
+ // of the file if it's included multiple times.
+ verifyFormat("#ifdef WIN32\n"
+ "# pragma once\n"
+ "#endif\n"
+ "#ifndef HEADER_H\n"
+ "# define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ "#ifdef WIN32\n"
+ "# pragma once\n"
+ "#endif\n"
+ "#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // FIXME: This does not detect when there is a single non-preprocessor line
+ // in front of an include-guard-like structure where other conditions hold
+ // because ScopedLineState hides the line.
+ verifyFormat("code();\n"
+ "#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ "code();\n"
+ "#ifndef HEADER_H\n"
+ "# define HEADER_H\n"
+ "code();\n"
+ "#endif",
+ Style);
+ // Keep comments aligned with #, otherwise indent comments normally. These
+ // tests cannot use verifyFormat because messUp manipulates leading
+ // whitespace.
+ {
+ const char *Expected = ""
+ "void f() {\n"
+ "#if 1\n"
+ "// Preprocessor aligned.\n"
+ "# define A 0\n"
+ " // Code. Separated by blank line.\n"
+ "\n"
+ "# define B 0\n"
+ " // Code. Not aligned with #\n"
+ "# define C 0\n"
+ "#endif";
+ const char *ToFormat = ""
+ "void f() {\n"
+ "#if 1\n"
+ "// Preprocessor aligned.\n"
+ "# define A 0\n"
+ "// Code. Separated by blank line.\n"
+ "\n"
+ "# define B 0\n"
+ " // Code. Not aligned with #\n"
+ "# define C 0\n"
+ "#endif";
+ verifyFormat(Expected, ToFormat, Style);
+ verifyNoChange(Expected, Style);
+ }
+ // Keep block quotes aligned.
+ {
+ const char *Expected = ""
+ "void f() {\n"
+ "#if 1\n"
+ "/* Preprocessor aligned. */\n"
+ "# define A 0\n"
+ " /* Code. Separated by blank line. */\n"
+ "\n"
+ "# define B 0\n"
+ " /* Code. Not aligned with # */\n"
+ "# define C 0\n"
+ "#endif";
+ const char *ToFormat = ""
+ "void f() {\n"
+ "#if 1\n"
+ "/* Preprocessor aligned. */\n"
+ "# define A 0\n"
+ "/* Code. Separated by blank line. */\n"
+ "\n"
+ "# define B 0\n"
+ " /* Code. Not aligned with # */\n"
+ "# define C 0\n"
+ "#endif";
+ verifyFormat(Expected, ToFormat, Style);
+ verifyNoChange(Expected, Style);
+ }
+ // Keep comments aligned with un-indented directives.
+ {
+ const char *Expected = ""
+ "void f() {\n"
+ "// Preprocessor aligned.\n"
+ "#define A 0\n"
+ " // Code. Separated by blank line.\n"
+ "\n"
+ "#define B 0\n"
+ " // Code. Not aligned with #\n"
+ "#define C 0\n";
+ const char *ToFormat = ""
+ "void f() {\n"
+ "// Preprocessor aligned.\n"
+ "#define A 0\n"
+ "// Code. Separated by blank line.\n"
+ "\n"
+ "#define B 0\n"
+ " // Code. Not aligned with #\n"
+ "#define C 0\n";
+ verifyFormat(Expected, ToFormat, Style);
+ verifyNoChange(Expected, Style);
+ }
+ // Test AfterHash with tabs.
+ {
+ FormatStyle Tabbed = Style;
+ Tabbed.UseTab = FormatStyle::UT_Always;
+ Tabbed.IndentWidth = 8;
+ Tabbed.TabWidth = 8;
+ verifyFormat("#ifdef _WIN32\n"
+ "#\tdefine A 0\n"
+ "#\tifdef VAR2\n"
+ "#\t\tdefine B 1\n"
+ "#\t\tinclude <someheader.h>\n"
+ "#\t\tdefine MACRO \\\n"
+ "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
+ "#\tendif\n"
+ "#else\n"
+ "#\tdefine A 1\n"
+ "#endif",
+ Tabbed);
+ }
+
+ // Regression test: Multiline-macro inside include guards.
+ verifyFormat("#ifndef HEADER_H\n"
+ "#define HEADER_H\n"
+ "#define A() \\\n"
+ " int i; \\\n"
+ " int j;\n"
+ "#endif // HEADER_H",
+ getLLVMStyleWithColumns(20));
+
+ Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
+ // Basic before hash indent tests
+ verifyFormat("#ifdef _WIN32\n"
+ " #define A 0\n"
+ " #ifdef VAR2\n"
+ " #define B 1\n"
+ " #include <someheader.h>\n"
+ " #define MACRO \\\n"
+ " some_very_long_func_aaaaaaaaaa();\n"
+ " #endif\n"
+ "#else\n"
+ " #define A 1\n"
+ "#endif",
+ Style);
+ verifyFormat("#if A\n"
+ " #define MACRO \\\n"
+ " void a(int x) { \\\n"
+ " b(); \\\n"
+ " c(); \\\n"
+ " d(); \\\n"
+ " e(); \\\n"
+ " f(); \\\n"
+ " }\n"
+ "#endif",
+ Style);
+ // Keep comments aligned with indented directives. These
+ // tests cannot use verifyFormat because messUp manipulates leading
+ // whitespace.
+ {
+ const char *Expected = "void f() {\n"
+ "// Aligned to preprocessor.\n"
+ "#if 1\n"
+ " // Aligned to code.\n"
+ " int a;\n"
+ " #if 1\n"
+ " // Aligned to preprocessor.\n"
+ " #define A 0\n"
+ " // Aligned to code.\n"
+ " int b;\n"
+ " #endif\n"
+ "#endif\n"
+ "}";
+ const char *ToFormat = "void f() {\n"
+ "// Aligned to preprocessor.\n"
+ "#if 1\n"
+ "// Aligned to code.\n"
+ "int a;\n"
+ "#if 1\n"
+ "// Aligned to preprocessor.\n"
+ "#define A 0\n"
+ "// Aligned to code.\n"
+ "int b;\n"
+ "#endif\n"
+ "#endif\n"
+ "}";
+ verifyFormat(Expected, ToFormat, Style);
+ verifyNoChange(Expected, Style);
+ }
+ {
+ const char *Expected = "void f() {\n"
+ "/* Aligned to preprocessor. */\n"
+ "#if 1\n"
+ " /* Aligned to code. */\n"
+ " int a;\n"
+ " #if 1\n"
+ " /* Aligned to preprocessor. */\n"
+ " #define A 0\n"
+ " /* Aligned to code. */\n"
+ " int b;\n"
+ " #endif\n"
+ "#endif\n"
+ "}";
+ const char *ToFormat = "void f() {\n"
+ "/* Aligned to preprocessor. */\n"
+ "#if 1\n"
+ "/* Aligned to code. */\n"
+ "int a;\n"
+ "#if 1\n"
+ "/* Aligned to preprocessor. */\n"
+ "#define A 0\n"
+ "/* Aligned to code. */\n"
+ "int b;\n"
+ "#endif\n"
+ "#endif\n"
+ "}";
+ verifyFormat(Expected, ToFormat, Style);
+ verifyNoChange(Expected, Style);
+ }
+
+ // Test single comment before preprocessor
+ verifyFormat("// Comment\n"
+ "\n"
+ "#if 1\n"
+ "#endif",
+ Style);
+
+ verifyFormat("#ifndef ABCDE\n"
+ " #define ABCDE 0\n"
+ "#endif\n"
+ "\n"
+ "#define FGHIJK",
+ "#ifndef ABCDE\n"
+ "#define ABCDE 0\n"
+ "#endif\n"
+ "\n"
+ "#define FGHIJK",
+ Style);
+
+ verifyFormat("#ifndef FOO_H\n"
+ "#define FOO_H\n"
+ "#include <iostream>\n"
+ "#endif\n"
+ "// comment",
+ Style);
+}
+
+TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
+ verifyFormat("{\n"
+ " {\n"
+ " a #c;\n"
+ " }\n"
+ "}");
+}
+
+TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
+ verifyFormat("#define A \\\n { \\\n {\nint i;",
+ "#define A { {\nint i;", getLLVMStyleWithColumns(11));
+ verifyFormat("#define A \\\n } \\\n }\nint i;",
+ "#define A } }\nint i;", getLLVMStyleWithColumns(11));
+}
+
+TEST_F(FormatTest, EscapedNewlines) {
+ FormatStyle Narrow = getLLVMStyleWithColumns(11);
+ verifyFormat("#define A \\\n int i; \\\n int j;",
+ "#define A \\\nint i;\\\n int j;", Narrow);
+ verifyFormat("#define A\n\nint i;", "#define A \\\n\n int i;");
+ verifyFormat("template <class T> f();", "\\\ntemplate <class T> f();");
+ verifyFormat("/* \\ \\ \\\n */", "\\\n/* \\ \\ \\\n */");
+ verifyNoChange("<a\n\\\\\n>");
+
+ FormatStyle AlignLeft = getLLVMStyle();
+ AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ verifyFormat("#define MACRO(x) \\\n"
+ "private: \\\n"
+ " int x(int a);",
+ AlignLeft);
+
+ // Escaped with a trigraph. The program just has to avoid crashing.
+ verifyNoCrash("#define A \?\?/\n"
+ "int i;\?\?/\n"
+ " int j;");
+ verifyNoCrash("#define A \?\?/\r\n"
+ "int i;\?\?/\r\n"
+ " int j;");
+ verifyNoCrash("#define A \?\?/\n"
+ "int i;",
+ getGoogleStyle(FormatStyle::LK_CSharp));
+
+ // CRLF line endings
+ verifyFormat("#define A \\\r\n int i; \\\r\n int j;",
+ "#define A \\\r\nint i;\\\r\n int j;", Narrow);
+ verifyFormat("#define A\r\n\r\nint i;", "#define A \\\r\n\r\n int i;");
+ verifyFormat("template <class T> f();", "\\\ntemplate <class T> f();");
+ verifyFormat("/* \\ \\ \\\r\n */", "\\\r\n/* \\ \\ \\\r\n */");
+ verifyNoChange("<a\r\n\\\\\r\n>");
+ verifyFormat("#define MACRO(x) \\\r\n"
+ "private: \\\r\n"
+ " int x(int a);",
+ AlignLeft);
+
+ constexpr StringRef Code("#define A \\\n"
+ " int a123; \\\n"
+ " int a; \\\n"
+ " int a1234;");
+ verifyFormat(Code, AlignLeft);
+
+ constexpr StringRef Code2("#define A \\\n"
+ " int a123; \\\n"
+ " int a; \\\n"
+ " int a1234;");
+ auto LastLine = getLLVMStyle();
+ LastLine.AlignEscapedNewlines = FormatStyle::ENAS_LeftWithLastLine;
+ verifyFormat(Code2, LastLine);
+
+ LastLine.ColumnLimit = 13;
+ verifyFormat(Code, LastLine);
+
+ LastLine.ColumnLimit = 0;
+ verifyFormat(Code2, LastLine);
+
+ FormatStyle DontAlign = getLLVMStyle();
+ DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
+ DontAlign.MaxEmptyLinesToKeep = 3;
+ // FIXME: can't use verifyFormat here because the newline before
+ // "public:" is not inserted the first time it's reformatted
+ verifyNoChange("#define A \\\n"
+ " class Foo { \\\n"
+ " void bar(); \\\n"
+ "\\\n"
+ "\\\n"
+ "\\\n"
+ " public: \\\n"
+ " void baz(); \\\n"
+ " };",
+ DontAlign);
+}
+
+TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
+ verifyFormat("#define A \\\n"
+ " int v( \\\n"
+ " a); \\\n"
+ " int i;",
+ getLLVMStyleWithColumns(11));
+}
+
+TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
+ verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
+ " \\\n"
+ " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
+ "\n"
+ "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
+ " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);",
+ " #define ALooooooooooooooooooooooooooooooooooooooongMacro("
+ "\\\n"
+ "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
+ " \n"
+ " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
+ " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);");
+}
+
+TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
+ verifyFormat("int\n"
+ "#define A\n"
+ " a;",
+ "int\n#define A\na;");
+ verifyFormat("functionCallTo(\n"
+ " someOtherFunction(\n"
+ " withSomeParameters, whichInSequence,\n"
+ " areLongerThanALine(andAnotherCall,\n"
+ "#define A B\n"
+ " withMoreParamters,\n"
+ " whichStronglyInfluenceTheLayout),\n"
+ " andMoreParameters),\n"
+ " trailing);",
+ getLLVMStyleWithColumns(69));
+ verifyFormat("Foo::Foo()\n"
+ "#ifdef BAR\n"
+ " : baz(0)\n"
+ "#endif\n"
+ "{\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " if (true)\n"
+ "#ifdef A\n"
+ " f(42);\n"
+ " x();\n"
+ "#else\n"
+ " g();\n"
+ " x();\n"
+ "#endif\n"
+ "}");
+ verifyFormat("void f(param1, param2,\n"
+ " param3,\n"
+ "#ifdef A\n"
+ " param4(param5,\n"
+ "#ifdef A1\n"
+ " param6,\n"
+ "#ifdef A2\n"
+ " param7),\n"
+ "#else\n"
+ " param8),\n"
+ " param9,\n"
+ "#endif\n"
+ " param10,\n"
+ "#endif\n"
+ " param11)\n"
+ "#else\n"
+ " param12)\n"
+ "#endif\n"
+ "{\n"
+ " x();\n"
+ "}",
+ getLLVMStyleWithColumns(28));
+ verifyFormat("#if 1\n"
+ "int i;");
+ verifyFormat("#if 1\n"
+ "#endif\n"
+ "#if 1\n"
+ "#else\n"
+ "#endif");
+ verifyFormat("DEBUG({\n"
+ " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
+ "});\n"
+ "#if a\n"
+ "#else\n"
+ "#endif");
+
+ verifyIncompleteFormat("void f(\n"
+ "#if A\n"
+ ");\n"
+ "#else\n"
+ "#endif");
+
+ // Verify that indentation is correct when there is an `#if 0` with an
+ // `#else`.
+ verifyFormat("#if 0\n"
+ "{\n"
+ "#else\n"
+ "{\n"
+ "#endif\n"
+ " x;\n"
+ "}");
+
+ verifyFormat("#if 0\n"
+ "#endif\n"
+ "#if X\n"
+ "int something_fairly_long; // Align here please\n"
+ "#endif // Should be aligned");
+
+ verifyFormat("#if 0\n"
+ "#endif\n"
+ "#if X\n"
+ "#else // Align\n"
+ ";\n"
+ "#endif // Align");
+
+ verifyFormat("void SomeFunction(int param1,\n"
+ " template <\n"
+ "#ifdef A\n"
+ "#if 0\n"
+ "#endif\n"
+ " MyType<Some>>\n"
+ "#else\n"
+ " Type1, Type2>\n"
+ "#endif\n"
+ " param2,\n"
+ " param3) {\n"
+ " f();\n"
+ "}");
+
+ verifyFormat("#ifdef __cplusplus\n"
+ "extern \"C\"\n"
+ "#endif\n"
+ " void f();");
+}
+
+TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
+ verifyFormat("#endif\n"
+ "#if B");
+}
+
+TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
+ FormatStyle SingleLine = getLLVMStyle();
+ SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
+ verifyFormat("#if 0\n"
+ "#elif 1\n"
+ "#endif\n"
+ "void foo() {\n"
+ " if (test) foo2();\n"
+ "}",
+ SingleLine);
+}
+
+TEST_F(FormatTest, LayoutBlockInsideParens) {
+ verifyFormat("functionCall({ int i; });");
+ verifyFormat("functionCall({\n"
+ " int i;\n"
+ " int j;\n"
+ "});");
+ verifyFormat("functionCall(\n"
+ " {\n"
+ " int i;\n"
+ " int j;\n"
+ " },\n"
+ " aaaa, bbbb, cccc);");
+ verifyFormat("functionA(functionB({\n"
+ " int i;\n"
+ " int j;\n"
+ " }),\n"
+ " aaaa, bbbb, cccc);");
+ verifyFormat("functionCall(\n"
+ " {\n"
+ " int i;\n"
+ " int j;\n"
+ " },\n"
+ " aaaa, bbbb, // comment\n"
+ " cccc);");
+ verifyFormat("functionA(functionB({\n"
+ " int i;\n"
+ " int j;\n"
+ " }),\n"
+ " aaaa, bbbb, // comment\n"
+ " cccc);");
+ verifyFormat("functionCall(aaaa, bbbb, { int i; });");
+ verifyFormat("functionCall(aaaa, bbbb, {\n"
+ " int i;\n"
+ " int j;\n"
+ "});");
+ verifyFormat(
+ "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
+ " {\n"
+ " int i; // break\n"
+ " },\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " ccccccccccccccccc));");
+ verifyFormat("DEBUG({\n"
+ " if (a)\n"
+ " f();\n"
+ "});");
+}
+
+TEST_F(FormatTest, LayoutBlockInsideStatement) {
+ verifyFormat("SOME_MACRO { int i; }\n"
+ "int i;",
+ " SOME_MACRO {int i;} int i;");
+}
+
+TEST_F(FormatTest, LayoutNestedBlocks) {
+ verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
+ " struct s {\n"
+ " int i;\n"
+ " };\n"
+ " s kBitsToOs[] = {{10}};\n"
+ " for (int i = 0; i < 10; ++i)\n"
+ " return;\n"
+ "}");
+ verifyFormat("call(parameter, {\n"
+ " something();\n"
+ " // Comment using all columns.\n"
+ " somethingelse();\n"
+ "});",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("DEBUG( //\n"
+ " { f(); }, a);");
+ verifyFormat("DEBUG( //\n"
+ " {\n"
+ " f(); //\n"
+ " },\n"
+ " a);");
+
+ verifyFormat("call(parameter, {\n"
+ " something();\n"
+ " // Comment too\n"
+ " // looooooooooong.\n"
+ " somethingElse();\n"
+ "});",
+ "call(parameter, {\n"
+ " something();\n"
+ " // Comment too looooooooooong.\n"
+ " somethingElse();\n"
+ "});",
+ getLLVMStyleWithColumns(29));
+ verifyFormat("DEBUG({ int i; });", "DEBUG({ int i; });");
+ verifyFormat("DEBUG({ // comment\n"
+ " int i;\n"
+ "});",
+ "DEBUG({ // comment\n"
+ "int i;\n"
+ "});");
+ verifyFormat("DEBUG({\n"
+ " int i;\n"
+ "\n"
+ " // comment\n"
+ " int j;\n"
+ "});",
+ "DEBUG({\n"
+ " int i;\n"
+ "\n"
+ " // comment\n"
+ " int j;\n"
+ "});");
+
+ verifyFormat("DEBUG({\n"
+ " if (a)\n"
+ " return;\n"
+ "});");
+ verifyGoogleFormat("DEBUG({\n"
+ " if (a) return;\n"
+ "});");
+ FormatStyle Style = getGoogleStyle();
+ Style.ColumnLimit = 45;
+ verifyFormat("Debug(\n"
+ " aaaaa,\n"
+ " {\n"
+ " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
+ " },\n"
+ " a);",
+ Style);
+
+ verifyFormat("SomeFunction({MACRO({ return output; }), b});");
+
+ verifyNoCrash("^{v^{a}}");
+}
+
+TEST_F(FormatTest, FormatNestedBlocksInMacros) {
+ verifyFormat("#define MACRO() \\\n"
+ " Debug(aaa, /* force line break */ \\\n"
+ " { \\\n"
+ " int i; \\\n"
+ " int j; \\\n"
+ " })",
+ "#define MACRO() Debug(aaa, /* force line break */ \\\n"
+ " { int i; int j; })",
+ getGoogleStyle());
+
+ verifyFormat("#define A \\\n"
+ " [] { \\\n"
+ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
+ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
+ " }",
+ "#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
+ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
+ getGoogleStyle());
+}
+
+TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
+ verifyFormat("enum E {};");
+ verifyFormat("enum E {}");
+ FormatStyle Style = getLLVMStyle();
+ Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
+ verifyFormat("void f() { }", "void f() {}", Style);
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
+ verifyFormat("{ }", Style);
+ verifyFormat("while (true) { }", "while (true) {}", Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeElse = false;
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
+ verifyFormat("if (a)\n"
+ "{\n"
+ "} else if (b)\n"
+ "{\n"
+ "} else\n"
+ "{ }",
+ Style);
+ Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
+ verifyFormat("if (a) {\n"
+ "} else if (b) {\n"
+ "} else {\n"
+ "}",
+ Style);
+ Style.BraceWrapping.BeforeElse = true;
+ verifyFormat("if (a) { }\n"
+ "else if (b) { }\n"
+ "else { }",
+ Style);
+
+ Style = getLLVMStyle(FormatStyle::LK_CSharp);
+ Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
+ verifyFormat("Event += () => { };", Style);
+}
+
+TEST_F(FormatTest, FormatBeginBlockEndMacros) {
+ FormatStyle Style = getLLVMStyle();
+ Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
+ Style.MacroBlockEnd = "^[A-Z_]+_END$";
+ verifyFormat("FOO_BEGIN\n"
+ " FOO_ENTRY\n"
+ "FOO_END",
+ Style);
+ verifyFormat("FOO_BEGIN\n"
+ " NESTED_FOO_BEGIN\n"
+ " NESTED_FOO_ENTRY\n"
+ " NESTED_FOO_END\n"
+ "FOO_END",
+ Style);
+ verifyFormat("FOO_BEGIN(Foo, Bar)\n"
+ " int x;\n"
+ " x = 1;\n"
+ "FOO_END(Baz)",
+ Style);
+
+ Style.RemoveBracesLLVM = true;
+ verifyNoCrash("for (;;)\n"
+ " FOO_BEGIN\n"
+ " foo();\n"
+ " FOO_END",
+ Style);
+}
+
+//===----------------------------------------------------------------------===//
+// Line break tests.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, PreventConfusingIndents) {
+ verifyFormat(
+ "void f() {\n"
+ " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
+ " parameter, parameter, parameter)),\n"
+ " SecondLongCall(parameter));\n"
+ "}");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaa]];");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa>;");
+ verifyFormat("int a = bbbb && ccc &&\n"
+ " fffff(\n"
+ "#define A Just forcing a new line\n"
+ " ddd);");
+}
+
+TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
+ verifyFormat(
+ "bool aaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
+ " bbbbbbbb();");
+ verifyFormat(
+ "bool aaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
+ " bbbbbbbb();");
+
+ verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
+ " ccccccccc == ddddddddddd;");
+ verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
+ " ccccccccc == ddddddddddd;");
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
+ " ccccccccc == ddddddddddd;");
+
+ verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
+ " aaaaaa) &&\n"
+ " bbbbbb && cccccc;");
+ verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
+ " aaaaaa) >>\n"
+ " bbbbbb;");
+ verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
+ " SourceMgr.getSpellingColumnNumber(\n"
+ " TheLine.Last->FormatTok.Tok.getLocation()) -\n"
+ " 1);");
+
+ verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
+ " cccccc) {\n}");
+ verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
+ " cccccc) {\n}");
+ verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
+ " cccccc) {\n}");
+ verifyFormat("b = a &&\n"
+ " // Comment\n"
+ " b.c && d;");
+
+ // If the LHS of a comparison is not a binary expression itself, the
+ // additional linebreak confuses many people.
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
+ "}");
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
+ "}");
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
+ "}");
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
+ "}");
+ // Even explicit parentheses stress the precedence enough to make the
+ // additional break unnecessary.
+ verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
+ "}");
+ // This cases is borderline, but with the indentation it is still readable.
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+ "}",
+ getLLVMStyleWithColumns(75));
+
+ // If the LHS is a binary expression, we should still use the additional break
+ // as otherwise the formatting hides the operator precedence.
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
+ " 5) {\n"
+ "}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
+ " 5) {\n"
+ "}");
+
+ FormatStyle OnePerLine = getLLVMStyle();
+ OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
+ OnePerLine);
+
+ verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
+ " .aaa(aaaaaaaaaaaaa) *\n"
+ " aaaaaaa +\n"
+ " aaaaaaa;",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, ExpressionIndentation) {
+ verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
+ " ccccccccccccccccccccccccccccccccccccccccc;");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
+ verifyFormat("if () {\n"
+ "} else if (aaaaa && bbbbb > // break\n"
+ " ccccc) {\n"
+ "}");
+ verifyFormat("if () {\n"
+ "} else if constexpr (aaaaa && bbbbb > // break\n"
+ " ccccc) {\n"
+ "}");
+ verifyFormat("if () {\n"
+ "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
+ " ccccc) {\n"
+ "}");
+ verifyFormat("if () {\n"
+ "} else if (aaaaa &&\n"
+ " bbbbb > // break\n"
+ " ccccc &&\n"
+ " ddddd) {\n"
+ "}");
+
+ // Presence of a trailing comment used to change indentation of b.
+ verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
+ " b;\n"
+ "return aaaaaaaaaaaaaaaaaaa +\n"
+ " b; //",
+ getLLVMStyleWithColumns(30));
+}
+
+TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
+ // Not sure what the best system is here. Like this, the LHS can be found
+ // immediately above an operator (everything with the same or a higher
+ // indent). The RHS is aligned right of the operator and so compasses
+ // everything until something with the same indent as the operator is found.
+ // FIXME: Is this a good system?
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat(
+ "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " > ccccccccccccccccccccccccccccccccccccccccc;",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if () {\n"
+ "} else if (aaaaa\n"
+ " && bbbbb // break\n"
+ " > ccccc) {\n"
+ "}",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ Style);
+ verifyFormat("return (a)\n"
+ " // comment\n"
+ " + b;",
+ Style);
+ verifyFormat(
+ "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + cc;",
+ Style);
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+
+ // Forced by comments.
+ verifyFormat(
+ "unsigned ContentSize =\n"
+ " sizeof(int16_t) // DWARF ARange version number\n"
+ " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
+ " + sizeof(int8_t) // Pointer Size (in bytes)\n"
+ " + sizeof(int8_t); // Segment Size (in bytes)");
+
+ verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
+ " == boost::fusion::at_c<1>(iiii).second;",
+ Style);
+
+ Style.ColumnLimit = 60;
+ verifyFormat("zzzzzzzzzz\n"
+ " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+
+ Style.ColumnLimit = 80;
+ Style.IndentWidth = 4;
+ Style.TabWidth = 4;
+ Style.UseTab = FormatStyle::UT_Always;
+ Style.AlignAfterOpenBracket = false;
+ Style.AlignOperands = FormatStyle::OAS_DontAlign;
+ verifyFormat("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
+ "\t&& (someOtherLongishConditionPart1\n"
+ "\t\t|| someOtherEvenLongerNestedConditionPart2);",
+ "return someVeryVeryLongConditionThatBarelyFitsOnALine && "
+ "(someOtherLongishConditionPart1 || "
+ "someOtherEvenLongerNestedConditionPart2);",
+ Style);
+
+ Style = getLLVMStyleWithColumns(20);
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ Style.ContinuationIndentWidth = 2;
+ verifyFormat("struct Foo {\n"
+ " Foo(\n"
+ " int arg1,\n"
+ " int arg2)\n"
+ " : Base(\n"
+ " arg1,\n"
+ " arg2) {}\n"
+ "};",
+ Style);
+ verifyFormat("return abc\n"
+ " ? foo(\n"
+ " a,\n"
+ " b,\n"
+ " bar(\n"
+ " abc))\n"
+ " : g(abc);",
+ Style);
+}
+
+TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
+
+ verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " > ccccccccccccccccccccccccccccccccccccccccc;",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+ Style);
+ verifyFormat("if () {\n"
+ "} else if (aaaaa\n"
+ " && bbbbb // break\n"
+ " > ccccc) {\n"
+ "}",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ Style);
+ verifyFormat("return (a)\n"
+ " // comment\n"
+ " + b;",
+ Style);
+ verifyFormat(
+ "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + cc;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : ccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee)\n"
+ " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+
+ verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
+ " == boost::fusion::at_c<1>(iiii).second;",
+ Style);
+
+ Style.ColumnLimit = 60;
+ verifyFormat("zzzzzzzzzzzzz\n"
+ " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+
+ // Forced by comments.
+ Style.ColumnLimit = 80;
+ verifyFormat(
+ "unsigned ContentSize\n"
+ " = sizeof(int16_t) // DWARF ARange version number\n"
+ " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
+ " + sizeof(int8_t) // Pointer Size (in bytes)\n"
+ " + sizeof(int8_t); // Segment Size (in bytes)",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ verifyFormat(
+ "unsigned ContentSize =\n"
+ " sizeof(int16_t) // DWARF ARange version number\n"
+ " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
+ " + sizeof(int8_t) // Pointer Size (in bytes)\n"
+ " + sizeof(int8_t); // Segment Size (in bytes)",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+ verifyFormat(
+ "unsigned ContentSize =\n"
+ " sizeof(int16_t) // DWARF ARange version number\n"
+ " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
+ " + sizeof(int8_t) // Pointer Size (in bytes)\n"
+ " + sizeof(int8_t); // Segment Size (in bytes)",
+ Style);
+}
+
+TEST_F(FormatTest, EnforcedOperatorWraps) {
+ // Here we'd like to wrap after the || operators, but a comment is forcing an
+ // earlier wrap.
+ verifyFormat("bool x = aaaaa //\n"
+ " || bbbbb\n"
+ " //\n"
+ " || cccc;");
+}
+
+TEST_F(FormatTest, NoOperandAlignment) {
+ FormatStyle Style = getLLVMStyle();
+ Style.AlignOperands = FormatStyle::OAS_DontAlign;
+ verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " > ccccccccccccccccccccccccccccccccccccccccc;",
+ Style);
+
+ verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " + cc;",
+ Style);
+ verifyFormat("int a = aa\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " * cccccccccccccccccccccccccccccccccccc;",
+ Style);
+
+ Style.AlignAfterOpenBracket = false;
+ verifyFormat("return (a > b\n"
+ " // comment1\n"
+ " // comment2\n"
+ " || c);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakingBeforeNonAssignmentOperators) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ Style);
+}
+
+TEST_F(FormatTest, AllowBinPackingInsideArguments) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ Style.BinPackArguments = false;
+ verifyFormat("void test() {\n"
+ " someFunction(\n"
+ " this + argument + is + quite\n"
+ " + long + so + it + gets + wrapped\n"
+ " + but + remains + bin - packed);\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " someFunction(arg1,\n"
+ " this + argument + is\n"
+ " + quite + long + so\n"
+ " + it + gets + wrapped\n"
+ " + but + remains + bin\n"
+ " - packed,\n"
+ " arg3);\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " someFunction(\n"
+ " arg1,\n"
+ " this + argument + has\n"
+ " + anotherFunc(nested,\n"
+ " calls + whose\n"
+ " + arguments\n"
+ " + are + also\n"
+ " + wrapped,\n"
+ " in + addition)\n"
+ " + to + being + bin - packed,\n"
+ " arg3);\n"
+ "}",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+ verifyFormat("void test() {\n"
+ " someFunction(\n"
+ " arg1,\n"
+ " this + argument + has +\n"
+ " anotherFunc(nested,\n"
+ " calls + whose +\n"
+ " arguments +\n"
+ " are + also +\n"
+ " wrapped,\n"
+ " in + addition) +\n"
+ " to + being + bin - packed,\n"
+ " arg3);\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
+ auto Style = getLLVMStyleWithColumns(45);
+ EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
+ verifyFormat("bool b =\n"
+ " is_default_constructible_v<hash<T>> and\n"
+ " is_copy_constructible_v<hash<T>> and\n"
+ " is_move_constructible_v<hash<T>> and\n"
+ " is_copy_assignable_v<hash<T>> and\n"
+ " is_move_assignable_v<hash<T>> and\n"
+ " is_destructible_v<hash<T>> and\n"
+ " is_swappable_v<hash<T>> and\n"
+ " is_callable_v<hash<T>(T)>;",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+ verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
+ " and is_copy_constructible_v<hash<T>>\n"
+ " and is_move_constructible_v<hash<T>>\n"
+ " and is_copy_assignable_v<hash<T>>\n"
+ " and is_move_assignable_v<hash<T>>\n"
+ " and is_destructible_v<hash<T>>\n"
+ " and is_swappable_v<hash<T>>\n"
+ " and is_callable_v<hash<T>(T)>;",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
+ " and is_copy_constructible_v<hash<T>>\n"
+ " and is_move_constructible_v<hash<T>>\n"
+ " and is_copy_assignable_v<hash<T>>\n"
+ " and is_move_assignable_v<hash<T>>\n"
+ " and is_destructible_v<hash<T>>\n"
+ " and is_swappable_v<hash<T>>\n"
+ " and is_callable_v<hash<T>(T)>;",
+ Style);
+}
+
+TEST_F(FormatTest, ConstructorInitializers) {
+ verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
+ verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
+ getLLVMStyleWithColumns(45));
+ verifyFormat("Constructor()\n"
+ " : Inttializer(FitsOnTheLine) {}",
+ getLLVMStyleWithColumns(44));
+ verifyFormat("Constructor()\n"
+ " : Inttializer(FitsOnTheLine) {}",
+ getLLVMStyleWithColumns(43));
+
+ verifyFormat("template <typename T>\n"
+ "Constructor() : Initializer(FitsOnTheLine) {}",
+ getLLVMStyleWithColumns(45));
+
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
+
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
+ verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " : aaaaaaaaaa(aaaaaa) {}");
+
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa() {}");
+
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
+
+ verifyFormat("Constructor(int Parameter = 0)\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
+ "}",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
+
+ // Here a line could be saved by splitting the second initializer onto two
+ // lines, but that is not desirable.
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaa(aaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
+
+ FormatStyle OnePerLine = getLLVMStyle();
+ OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
+ verifyFormat("MyClass::MyClass()\n"
+ " : a(a),\n"
+ " b(b),\n"
+ " c(c) {}",
+ OnePerLine);
+ verifyFormat("MyClass::MyClass()\n"
+ " : a(a), // comment\n"
+ " b(b),\n"
+ " c(c) {}",
+ OnePerLine);
+ verifyFormat("MyClass::MyClass(int a)\n"
+ " : b(a), // comment\n"
+ " c(a + 1) { // lined up\n"
+ "}",
+ OnePerLine);
+ verifyFormat("Constructor()\n"
+ " : a(b, b, b) {}",
+ OnePerLine);
+ OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ verifyFormat("MyClass::MyClass(int var)\n"
+ " : some_var_(var), // 4 space indent\n"
+ " some_other_var_(var + 1) { // lined up\n"
+ "}",
+ OnePerLine);
+ verifyFormat("Constructor()\n"
+ " : aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa) {}",
+ OnePerLine);
+ verifyFormat("Constructor()\n"
+ " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat(
+ "Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaa().aaa(),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ OnePerLine.ColumnLimit = 60;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
+ OnePerLine);
+
+ verifyFormat("Constructor()\n"
+ " : // Comment forcing unwanted break.\n"
+ " aaaa(aaaa) {}",
+ "Constructor() :\n"
+ " // Comment forcing unwanted break.\n"
+ " aaaa(aaaa) {}");
+
+ // Braced initializers with trailing commas.
+ verifyFormat("MyClass::MyClass()\n"
+ " : aaaa{\n"
+ " 0,\n"
+ " },\n"
+ " bbbb{\n"
+ " 0,\n"
+ " } {}",
+ "MyClass::MyClass():aaaa{0,},bbbb{0,}{}");
+}
+
+TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
+ FormatStyle Style = getLLVMStyleWithColumns(60);
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+
+ for (int i = 0; i < 4; ++i) {
+ // Test all combinations of parameters that should not have an effect.
+ Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
+ Style.AllowAllArgumentsOnNextLine = i & 2;
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+ verifyFormat("Constructor() : a(a), b(b) {}", Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a)\n"
+ " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+ verifyFormat("Constructor() : a(a), b(b) {}", Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+ verifyFormat("Constructor()\n"
+ " : a(a), b(b) {}",
+ Style);
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a)\n"
+ " , bbbbbbbbbbbbbbbbbbbbb(b)\n"
+ " , cccccccccccccccccccccc(c) {}",
+ Style);
+
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+ verifyFormat("Constructor()\n"
+ " : a(a), b(b) {}",
+ Style);
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b),\n"
+ " cccccccccccccccccccccc(c) {}",
+ Style);
+
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+ verifyFormat("Constructor() :\n"
+ " a(a), b(b) {}",
+ Style);
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b),\n"
+ " cccccccccccccccccccccc(c) {}",
+ Style);
+ }
+
+ // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
+ // AllowAllConstructorInitializersOnNextLine in all
+ // BreakConstructorInitializers modes
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ Style.AllowAllParametersOfDeclarationOnNextLine = true;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a)\n"
+ " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.AllowAllParametersOfDeclarationOnNextLine = false;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a)\n"
+ " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
+
+ Style.AllowAllParametersOfDeclarationOnNextLine = true;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.AllowAllParametersOfDeclarationOnNextLine = false;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb)\n"
+ " : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
+ Style.AllowAllParametersOfDeclarationOnNextLine = true;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc) :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb,\n"
+ " int cccccccccccccccc) :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.AllowAllParametersOfDeclarationOnNextLine = false;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb) :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style = getLLVMStyleWithColumns(0);
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("Foo(Bar bar, Baz baz) : bar(bar), baz(baz) {}", Style);
+ verifyNoChange("Foo(Bar bar, Baz baz)\n"
+ " : bar(bar), baz(baz) {}",
+ Style);
+}
+
+TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
+ FormatStyle Style = getLLVMStyleWithColumns(60);
+ Style.BinPackArguments = false;
+ for (int i = 0; i < 4; ++i) {
+ // Test all combinations of parameters that should not have an effect.
+ Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
+ Style.PackConstructorInitializers =
+ i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
+
+ Style.AllowAllArgumentsOnNextLine = true;
+ verifyFormat("void foo() {\n"
+ " FunctionCallWithReallyLongName(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
+ "}",
+ Style);
+ Style.AllowAllArgumentsOnNextLine = false;
+ verifyFormat("void foo() {\n"
+ " FunctionCallWithReallyLongName(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbb);\n"
+ "}",
+ Style);
+
+ Style.AllowAllArgumentsOnNextLine = true;
+ verifyFormat("void foo() {\n"
+ " auto VariableWithReallyLongName = {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
+ "}",
+ Style);
+ Style.AllowAllArgumentsOnNextLine = false;
+ verifyFormat("void foo() {\n"
+ " auto VariableWithReallyLongName = {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbb};\n"
+ "}",
+ Style);
+ }
+
+ // This parameter should not affect declarations.
+ Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ Style.AllowAllArgumentsOnNextLine = false;
+ Style.AllowAllParametersOfDeclarationOnNextLine = true;
+ verifyFormat("void FunctionCallWithReallyLongName(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
+ Style);
+ Style.AllowAllParametersOfDeclarationOnNextLine = false;
+ verifyFormat("void FunctionCallWithReallyLongName(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbb);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakFunctionDefinitionParameters) {
+ StringRef Input = "void functionDecl(paramA, paramB, paramC);\n"
+ "void emptyFunctionDefinition() {}\n"
+ "void functionDefinition(int A, int B, int C) {}\n"
+ "Class::Class(int A, int B) : m_A(A), m_B(B) {}";
+ verifyFormat(Input);
+
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_FALSE(Style.BreakFunctionDefinitionParameters);
+ Style.BreakFunctionDefinitionParameters = true;
+ verifyFormat("void functionDecl(paramA, paramB, paramC);\n"
+ "void emptyFunctionDefinition() {}\n"
+ "void functionDefinition(\n"
+ " int A, int B, int C) {}\n"
+ "Class::Class(\n"
+ " int A, int B)\n"
+ " : m_A(A), m_B(B) {}",
+ Input, Style);
+
+ // Test the style where all parameters are on their own lines.
+ Style.AllowAllParametersOfDeclarationOnNextLine = false;
+ Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("void functionDecl(paramA, paramB, paramC);\n"
+ "void emptyFunctionDefinition() {}\n"
+ "void functionDefinition(\n"
+ " int A,\n"
+ " int B,\n"
+ " int C) {}\n"
+ "Class::Class(\n"
+ " int A,\n"
+ " int B)\n"
+ " : m_A(A), m_B(B) {}",
+ Input, Style);
+}
+
+TEST_F(FormatTest, BreakBeforeInlineASMColon) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Never;
+ /* Test the behaviour with long lines */
+ Style.ColumnLimit = 40;
+ verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
+ " : : val);",
+ Style);
+ verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
+ " : val1 : val2);",
+ Style);
+ verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " \"cpuid\\n\\t\"\n"
+ " \"xchgq\\t%%rbx %%rsi\\n\\t\",\n"
+ " : \"=a\" : \"a\");",
+ Style);
+ Style.ColumnLimit = 80;
+ verifyFormat("asm volatile(\"string\", : : val);", Style);
+ verifyFormat("asm volatile(\"string\", : val1 : val2);", Style);
+
+ Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Always;
+ verifyFormat("asm volatile(\"string\",\n"
+ " :\n"
+ " : val);",
+ Style);
+ verifyFormat("asm volatile(\"string\",\n"
+ " : val1\n"
+ " : val2);",
+ Style);
+ /* Test the behaviour with long lines */
+ Style.ColumnLimit = 40;
+ verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " \"cpuid\\n\\t\"\n"
+ " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " : \"=a\"(*rEAX)\n"
+ " : \"a\"(value));",
+ Style);
+ verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " \"cpuid\\n\\t\"\n"
+ " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
+ " :\n"
+ " : \"a\"(value));",
+ Style);
+ verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
+ " :\n"
+ " : val);",
+ Style);
+ verifyFormat("asm volatile(\"loooooooooooooooooooong\",\n"
+ " : val1\n"
+ " : val2);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
+
+ verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
+ verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
+ getStyleWithColumns(Style, 45));
+ verifyFormat("Constructor() :\n"
+ " Initializer(FitsOnTheLine) {}",
+ getStyleWithColumns(Style, 44));
+ verifyFormat("Constructor() :\n"
+ " Initializer(FitsOnTheLine) {}",
+ getStyleWithColumns(Style, 43));
+
+ verifyFormat("template <typename T>\n"
+ "Constructor() : Initializer(FitsOnTheLine) {}",
+ getStyleWithColumns(Style, 50));
+ verifyFormat(
+ "Class::Class(int some, int arguments, int loooooooooooooooooooong,\n"
+ " int mooooooooooooore) noexcept :\n"
+ " Super{some, arguments}, Member{5}, Member2{2} {}",
+ Style);
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat(
+ "SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat(
+ "SomeClass::Constructor() : // NOLINT\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat(
+ "SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat(
+ "SomeClass::Constructor() : // NOLINT\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
+ verifyFormat(
+ "SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ verifyFormat(
+ "SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat(
+ "SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat(
+ "Ctor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) : aaaaaaaaaa(aaaaaa) {}",
+ Style);
+
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa() {}",
+ Style);
+
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ Style);
+
+ verifyFormat("Constructor(int Parameter = 0) :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
+ "}",
+ getStyleWithColumns(Style, 60));
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
+ Style);
+
+ // Here a line could be saved by splitting the second initializer onto two
+ // lines, but that is not desirable.
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaa(aaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ Style);
+
+ FormatStyle OnePerLine = Style;
+ OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ verifyFormat("SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ verifyFormat("Foo::Foo(int i, int j) : // NOLINT\n"
+ " i(i), // comment\n"
+ " j(j) {}",
+ OnePerLine);
+ verifyFormat("MyClass::MyClass(int var) :\n"
+ " some_var_(var), // 4 space indent\n"
+ " some_other_var_(var + 1) { // lined up\n"
+ "}",
+ OnePerLine);
+ verifyFormat("Constructor() :\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa),\n"
+ " aaaaa(aaaaaa) {}",
+ OnePerLine);
+ verifyFormat("Constructor() :\n"
+ " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaa().aaa(),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ OnePerLine);
+ OnePerLine.ColumnLimit = 60;
+ verifyFormat("Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
+ OnePerLine);
+
+ verifyFormat("Constructor() :\n"
+ " // Comment forcing unwanted break.\n"
+ " aaaa(aaaa) {}",
+ Style);
+ verifyFormat("Constructor() : // NOLINT\n"
+ " aaaa(aaaa) {}",
+ Style);
+ verifyFormat("Constructor() : // A very long trailing comment that cannot fit"
+ " on a single\n"
+ " // line.\n"
+ " aaaa(aaaa) {}",
+ "Constructor() : // A very long trailing comment that cannot fit"
+ " on a single line.\n"
+ " aaaa(aaaa) {}",
+ Style);
+
+ Style.ColumnLimit = 0;
+ verifyNoChange("SomeClass::Constructor() :\n"
+ " a(a) {}",
+ Style);
+ verifyNoChange("SomeClass::Constructor() noexcept :\n"
+ " a(a) {}",
+ Style);
+ verifyNoChange("SomeClass::Constructor() :\n"
+ " a(a), b(b), c(c) {}",
+ Style);
+ verifyNoChange("SomeClass::Constructor() :\n"
+ " a(a) {\n"
+ " foo();\n"
+ " bar();\n"
+ "}",
+ Style);
+ verifyFormat("struct Foo {\n"
+ " int x;\n"
+ " Foo() : x(0) {}\n"
+ "};",
+ "struct Foo {\n"
+ " int x;\n"
+ " Foo():x(0) {}\n"
+ "};",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ verifyNoChange("SomeClass::Constructor() :\n"
+ " a(a), b(b), c(c) {\n"
+ "}",
+ Style);
+ verifyNoChange("SomeClass::Constructor() :\n"
+ " a(a) {\n"
+ "}",
+ Style);
+
+ Style.ColumnLimit = 80;
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ Style.ConstructorInitializerIndentWidth = 2;
+ verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
+ verifyFormat("SomeClass::Constructor() :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
+ Style);
+
+ // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
+ // well
+ Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
+ verifyFormat(
+ "class SomeClass\n"
+ " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
+ Style);
+ Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+ verifyFormat(
+ "class SomeClass\n"
+ " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
+ Style);
+ Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
+ verifyFormat(
+ "class SomeClass :\n"
+ " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
+ Style);
+ Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
+ verifyFormat(
+ "class SomeClass\n"
+ " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
+ Style);
+}
+
+TEST_F(FormatTest, BreakConstructorInitializersAfterComma) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterComma;
+
+ verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", Style);
+ verifyFormat("Constructor() : a(a), b(b), c(c) {}", Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat("SomeClassWithALongName::Constructor(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb) : aaaaaaaaaaaaaaaaaaaa(a),\n"
+ " bbbbbbbbbbbbbbbbbbbbb(b) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
+ Style);
+
+ Style.ColumnLimit = 0;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
+ verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
+ verifyNoChange("SomeClass::Constructor() : a(a),\n"
+ " b(b),\n"
+ " c(c) {}",
+ Style);
+}
+
+#ifndef EXPENSIVE_CHECKS
+// Expensive checks enables libstdc++ checking which includes validating the
+// state of ranges used in std::priority_queue - this blows out the
+// runtime/scalability of the function and makes this test unacceptably slow.
+TEST_F(FormatTest, MemoizationTests) {
+ // This breaks if the memoization lookup does not take \c Indent and
+ // \c LastSpace into account.
+ verifyFormat(
+ "extern CFRunLoopTimerRef\n"
+ "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
+ " CFTimeInterval interval, CFOptionFlags flags,\n"
+ " CFIndex order, CFRunLoopTimerCallBack callout,\n"
+ " CFRunLoopTimerContext *context) {}");
+
+ // Deep nesting somewhat works around our memoization.
+ verifyFormat(
+ "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
+ " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
+ " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
+ " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
+ " aaaaa())))))))))))))))))))))))))))))))))))))));",
+ getLLVMStyleWithColumns(65));
+ verifyFormat(
+ "aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa(\n"
+ " aaaaa,\n"
+ " aaaaa))))))))))));",
+ getLLVMStyleWithColumns(65));
+ verifyFormat(
+ "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a),\n"
+ " a)",
+ getLLVMStyleWithColumns(65));
+
+ // This test takes VERY long when memoization is broken.
+ FormatStyle OnePerLine = getLLVMStyle();
+ OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ OnePerLine.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ std::string input = "Constructor()\n"
+ " : aaaa(a,\n";
+ for (unsigned i = 0, e = 80; i != e; ++i)
+ input += " a,\n";
+ input += " a) {}";
+ verifyFormat(input, OnePerLine);
+ OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat(input, OnePerLine);
+}
+#endif
+
+TEST_F(FormatTest, BreaksAsHighAsPossible) {
+ verifyFormat(
+ "void f() {\n"
+ " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
+ " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
+ " f();\n"
+ "}");
+ verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
+ " Intervals[i - 1].getRange().getLast()) {\n}");
+}
+
+TEST_F(FormatTest, BreaksFunctionDeclarations) {
+ // Principially, we break function declarations in a certain order:
+ // 1) break amongst arguments.
+ verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
+ " Cccccccccccccc cccccccccccccc);");
+ verifyFormat("template <class TemplateIt>\n"
+ "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
+ " TemplateIt *stop) {}");
+
+ // 2) break after return type.
+ verifyGoogleFormat(
+ "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);");
+
+ // 3) break after (.
+ verifyGoogleFormat(
+ "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
+ " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);");
+
+ // 4) break before after nested name specifiers.
+ verifyGoogleFormat(
+ "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);");
+
+ // However, there are exceptions, if a sufficient amount of lines can be
+ // saved.
+ // FIXME: The precise cut-offs wrt. the number of saved lines might need some
+ // more adjusting.
+ verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc);");
+ verifyGoogleFormat(
+ "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
+ verifyFormat(
+ "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc);");
+ verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
+ " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
+
+ // Break after multi-line parameters.
+ verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbb bbbb);");
+ verifyFormat("void SomeLoooooooooooongFunction(\n"
+ " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbb);");
+
+ // Treat overloaded operators like other functions.
+ verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
+ "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
+ verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
+ "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
+ verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
+ "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
+ verifyGoogleFormat(
+ "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
+ " const SomeLooooooooogType& a, const SomeLooooooooogType& b);");
+ verifyGoogleFormat(
+ "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
+ " const SomeLooooooooogType& a, const SomeLooooooooogType& b);");
+
+ verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
+ "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
+ verifyGoogleFormat(
+ "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
+ "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " bool* aaaaaaaaaaaaaaaaaa, bool* aa) {}");
+ verifyGoogleFormat("template <typename T>\n"
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
+
+ verifyFormat("extern \"C\" //\n"
+ " void f();");
+
+ auto Style = getLLVMStyle();
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
+ Style);
+ verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ Style);
+
+ Style = getLLVMStyleWithColumns(45);
+ Style.PenaltyReturnTypeOnItsOwnLine = 400;
+ verifyFormat("template <bool abool, // a comment\n"
+ " bool anotherbool>\n"
+ "static inline std::pair<size_t, MyCustomType>\n"
+ "myfunc(const char *buf, const char *&err);",
+ Style);
+}
+
+TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
+ // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
+ // Prefer keeping `::` followed by `operator` together.
+ verifyFormat("const aaaa::bbbbbbb &\n"
+ "ccccccccc::operator++() {\n"
+ " stuff();\n"
+ "}",
+ "const aaaa::bbbbbbb\n"
+ "&ccccccccc::operator++() { stuff(); }",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, TrailingReturnType) {
+ verifyFormat("auto foo() -> int;");
+ // correct trailing return type spacing
+ verifyFormat("auto operator->() -> int;");
+ verifyFormat("auto operator++(int) -> int;");
+
+ verifyFormat("struct S {\n"
+ " auto bar() const -> int;\n"
+ "};");
+ verifyFormat("template <size_t Order, typename T>\n"
+ "auto load_img(const std::string &filename)\n"
+ " -> alias::tensor<Order, T, mem::tag::cpu> {}");
+ verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
+ " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
+ verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
+ verifyFormat("template <typename T>\n"
+ "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
+ " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
+
+ FormatStyle Style = getLLVMStyleWithColumns(60);
+ verifyFormat("#define MAKE_DEF(NAME) \\\n"
+ " auto NAME() -> int { return 42; }",
+ Style);
+
+ // Not trailing return types.
+ verifyFormat("void f() { auto a = b->c(); }");
+ verifyFormat("auto a = p->foo();");
+ verifyFormat("int a = p->foo();");
+ verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
+}
+
+TEST_F(FormatTest, DeductionGuides) {
+ verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
+ verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
+ verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
+ verifyFormat(
+ "template <class... T>\n"
+ "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
+ verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
+ verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
+ verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
+ verifyFormat("template <class T> A() -> A<(3 < 2)>;");
+ verifyFormat("template <class T> A() -> A<((3) < (2))>;");
+ verifyFormat("template <class T> x() -> x<1>;");
+ verifyFormat("template <class T> explicit x(T &) -> x<1>;");
+
+ verifyFormat("A(const char *) -> A<string &>;");
+ verifyFormat("A() -> A<int>;");
+
+ // Ensure not deduction guides.
+ verifyFormat("c()->f<int>();");
+ verifyFormat("x()->foo<1>;");
+ verifyFormat("x = p->foo<3>();");
+ verifyFormat("x()->x<1>();");
+}
+
+TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
+ // Avoid breaking before trailing 'const' or other trailing annotations, if
+ // they are not function-like.
+ FormatStyle Style = getGoogleStyleWithColumns(47);
+ verifyFormat("void someLongFunction(\n"
+ " int someLoooooooooooooongParameter) const {\n}",
+ getLLVMStyleWithColumns(47));
+ verifyFormat("LoooooongReturnType\n"
+ "someLoooooooongFunction() const {}",
+ getLLVMStyleWithColumns(47));
+ verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
+ " const {}",
+ Style);
+ verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
+ verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
+ verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
+ verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
+ " aaaaaaaaaaa aaaaa) const override;");
+ verifyGoogleFormat(
+ "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " const override;");
+
+ // Even if the first parameter has to be wrapped.
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) const {}",
+ getLLVMStyleWithColumns(46));
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) const {}",
+ Style);
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) override {}",
+ Style);
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) OVERRIDE {}",
+ Style);
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) final {}",
+ Style);
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) FINAL {}",
+ Style);
+ verifyFormat("void someLongFunction(\n"
+ " int parameter) const override {}",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) const\n"
+ "{\n"
+ "}",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
+ verifyFormat("void someLongFunction(\n"
+ " int someLongParameter) const\n"
+ " {\n"
+ " }",
+ Style);
+
+ // Unless these are unknown annotations.
+ verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " LONG_AND_UGLY_ANNOTATION;");
+
+ // Breaking before function-like trailing annotations is fine to keep them
+ // close to their arguments.
+ verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
+ verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
+ " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
+ verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
+ " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
+ verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
+ " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
+ verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
+
+ verifyFormat(
+ "void aaaaaaaaaaaaaaaaaa()\n"
+ " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa));");
+ verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " __attribute__((unused));");
+
+ Style = getGoogleStyle();
+
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " GUARDED_BY(aaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " GUARDED_BY(aaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
+ " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ABSL_GUARDED_BY(aaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ABSL_GUARDED_BY(aaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ABSL_GUARDED_BY(aaaaaaaaaaaa) =\n"
+ " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ABSL_GUARDED_BY(aaaaaaaaaaaa) =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+}
+
+TEST_F(FormatTest, FunctionAnnotations) {
+ verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
+ "int OldFunction(const string ¶meter) {}");
+ verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
+ "string OldFunction(const string ¶meter) {}");
+ verifyFormat("template <typename T>\n"
+ "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
+ "string OldFunction(const string ¶meter) {}");
+
+ // Not function annotations.
+ verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
+ verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
+ " ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
+ verifyFormat("MACRO(abc).function() // wrap\n"
+ " << abc;");
+ verifyFormat("MACRO(abc)->function() // wrap\n"
+ " << abc;");
+ verifyFormat("MACRO(abc)::function() // wrap\n"
+ " << abc;");
+ verifyFormat("FOO(bar)();", getLLVMStyleWithColumns(0));
+}
+
+TEST_F(FormatTest, BreaksDesireably) {
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
+ " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
+ " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
+ "}");
+
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
+
+ verifyFormat(
+ "aaaaaaaa(aaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
+ " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat(
+ "void f() {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
+ "}");
+ verifyFormat(
+ "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
+ verifyFormat(
+ "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
+ verifyFormat(
+ "aaaaaa(aaa,\n"
+ " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ // Indent consistently independent of call expression and unary operator.
+ verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
+ " dddddddddddddddddddddddddddddd));");
+ verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
+ " dddddddddddddddddddddddddddddd));");
+ verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
+ " dddddddddddddddddddddddddddddd));");
+
+ // This test case breaks on an incorrect memoization, i.e. an optimization not
+ // taking into account the StopAt value.
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("{\n {\n {\n"
+ " Annotation.SpaceRequiredBefore =\n"
+ " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
+ " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
+ " }\n }\n}");
+
+ // Break on an outer level if there was a break on an inner level.
+ verifyFormat("f(g(h(a, // comment\n"
+ " b, c),\n"
+ " d, e),\n"
+ " x, y);",
+ "f(g(h(a, // comment\n"
+ " b, c), d, e), x, y);");
+
+ // Prefer breaking similar line breaks.
+ verifyFormat(
+ "const int kTrackingOptions = NSTrackingMouseMoved |\n"
+ " NSTrackingMouseEnteredAndExited |\n"
+ " NSTrackingActiveAlways;");
+}
+
+TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
+ FormatStyle NoBinPacking = getGoogleStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ NoBinPacking.BinPackArguments = true;
+ verifyFormat("void f() {\n"
+ " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
+ "}",
+ NoBinPacking);
+ verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
+ " int aaaaaaaaaaaaaaaaaaaa,\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ NoBinPacking);
+
+ NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
+ verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " vector<int> bbbbbbbbbbbbbbb);",
+ NoBinPacking);
+ // FIXME: This behavior difference is probably not wanted. However, currently
+ // we cannot distinguish BreakBeforeParameter being set because of the wrapped
+ // template arguments from BreakBeforeParameter being set because of the
+ // one-per-line formatting.
+ verifyFormat(
+ "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaa> aaaaaaaaaa);",
+ NoBinPacking);
+ verifyFormat(
+ "void fffffffffff(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
+ " aaaaaaaaaa);");
+}
+
+TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
+ FormatStyle NoBinPacking = getGoogleStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ NoBinPacking.BinPackArguments = false;
+ verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
+ NoBinPacking);
+ verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
+ NoBinPacking);
+ verifyFormat(
+ "aaaaaaaa(aaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
+ " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
+ NoBinPacking);
+ verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaaaaa();",
+ NoBinPacking);
+ verifyFormat("void f() {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
+ "}",
+ NoBinPacking);
+
+ verifyFormat(
+ "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaa);",
+ NoBinPacking);
+ verifyFormat(
+ "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
+ " ddddddddddddddddddddddddddddd),\n"
+ " test);",
+ NoBinPacking);
+
+ verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa>\n"
+ " aaaaaaaaaaaaaaaaaa;",
+ NoBinPacking);
+ verifyFormat("a(\"a\"\n"
+ " \"a\",\n"
+ " a);");
+
+ NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
+ verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
+ " aaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ NoBinPacking);
+ verifyFormat(
+ "void f() {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaa();\n"
+ "}",
+ NoBinPacking);
+ verifyFormat(
+ "template <class SomeType, class SomeOtherType>\n"
+ "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
+ NoBinPacking);
+}
+
+TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
+ FormatStyle Style = getLLVMStyleWithColumns(15);
+ Style.ExperimentalAutoDetectBinPacking = true;
+ verifyFormat("aaa(aaaa,\n"
+ " aaaa,\n"
+ " aaaa);\n"
+ "aaa(aaaa,\n"
+ " aaaa,\n"
+ " aaaa);",
+ "aaa(aaaa,\n" // one-per-line
+ " aaaa,\n"
+ " aaaa );\n"
+ "aaa(aaaa, aaaa, aaaa);", // inconclusive
+ Style);
+ verifyFormat("aaa(aaaa, aaaa,\n"
+ " aaaa);\n"
+ "aaa(aaaa, aaaa,\n"
+ " aaaa);",
+ "aaa(aaaa, aaaa,\n" // bin-packed
+ " aaaa );\n"
+ "aaa(aaaa, aaaa, aaaa);", // inconclusive
+ Style);
+}
+
+TEST_F(FormatTest, IndentExportBlock) {
+ FormatStyle Style = getLLVMStyleWithColumns(80);
+ Style.IndentExportBlock = true;
+ verifyFormat("export {\n"
+ " int x;\n"
+ " int y;\n"
+ "}",
+ "export {\n"
+ "int x;\n"
+ "int y;\n"
+ "}",
+ Style);
+
+ Style.IndentExportBlock = false;
+ verifyFormat("export {\n"
+ "int x;\n"
+ "int y;\n"
+ "}",
+ "export {\n"
+ " int x;\n"
+ " int y;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, ShortExportBlocks) {
+ FormatStyle Style = getLLVMStyleWithColumns(80);
+ Style.IndentExportBlock = false;
+
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+ verifyFormat("export {\n"
+ "}",
+ Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ "export\n"
+ "{\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export {\n"
+ "}",
+ "export {}", Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ "export { int x; }", Style);
+
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ verifyFormat("export {}",
+ "export {\n"
+ "}",
+ Style);
+
+ verifyFormat("export { int x; }",
+ "export {\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export { int x; }",
+ "export\n"
+ "{\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export {}",
+ "export {\n"
+ "}",
+ Style);
+
+ verifyFormat("export { int x; }",
+ "export {\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
+ verifyFormat("export {}",
+ "export {\n"
+ "}",
+ Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ "export\n"
+ "{\n"
+ "int x;\n"
+ "}",
+ Style);
+
+ verifyFormat("export {}", Style);
+
+ verifyFormat("export {\n"
+ "int x;\n"
+ "}",
+ "export { int x; }", Style);
+}
+
+TEST_F(FormatTest, FormatsBuilderPattern) {
+ verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
+ " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
+ " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
+ " .StartsWith(\".init\", ORDER_INIT)\n"
+ " .StartsWith(\".fini\", ORDER_FINI)\n"
+ " .StartsWith(\".hash\", ORDER_HASH)\n"
+ " .Default(ORDER_TEXT);");
+
+ verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
+ " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
+ verifyFormat("aaaaaaa->aaaaaaa\n"
+ " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaa->aaaaaaa\n"
+ " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
+ " aaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
+ " aaaaaa->aaaaaaaaaaaa()\n"
+ " ->aaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " ->aaaaaaaaaaaaaaaaa();");
+ verifyGoogleFormat(
+ "void f() {\n"
+ " someo->Add((new util::filetools::Handler(dir))\n"
+ " ->OnEvent1(NewPermanentCallback(\n"
+ " this, &HandlerHolderClass::EventHandlerCBA))\n"
+ " ->OnEvent2(NewPermanentCallback(\n"
+ " this, &HandlerHolderClass::EventHandlerCBB))\n"
+ " ->OnEvent3(NewPermanentCallback(\n"
+ " this, &HandlerHolderClass::EventHandlerCBC))\n"
+ " ->OnEvent5(NewPermanentCallback(\n"
+ " this, &HandlerHolderClass::EventHandlerCBD))\n"
+ " ->OnEvent6(NewPermanentCallback(\n"
+ " this, &HandlerHolderClass::EventHandlerCBE)));\n"
+ "}");
+
+ verifyFormat(
+ "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
+ verifyFormat("aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa();");
+ verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa();");
+ verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaa();");
+ verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " ->aaaaaaaaaaaaaae(0)\n"
+ " ->aaaaaaaaaaaaaaa();");
+
+ // Don't linewrap after very short segments.
+ verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("aaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " .has<bbbbbbbbbbbbbbbbbbbbb>();");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
+
+ // Prefer not to break after empty parentheses.
+ verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
+ " First->LastNewlineOffset);");
+
+ // Prefer not to create "hanging" indents.
+ verifyFormat(
+ "return !soooooooooooooome_map\n"
+ " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .second;");
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
+ " .aaaa(aaaaaaaaaaaaaa);");
+ // No hanging indent here.
+ verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("aaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ getLLVMStyleWithColumns(59));
+ verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ // Dont break if only closing statements before member call
+ verifyFormat("test() {\n"
+ " ([]() -> {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " }).foo();\n"
+ "}");
+ verifyFormat("test() {\n"
+ " (\n"
+ " []() -> {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " },\n"
+ " foo, bar)\n"
+ " .foo();\n"
+ "}");
+ verifyFormat("test() {\n"
+ " ([]() -> {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " })\n"
+ " .foo()\n"
+ " .bar();\n"
+ "}");
+ verifyFormat("test() {\n"
+ " ([]() -> {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " })\n"
+ " .foo(\"aaaaaaaaaaaaaaaaa\"\n"
+ " \"bbbb\");\n"
+ "}",
+ getLLVMStyleWithColumns(30));
+}
+
+TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
+
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
+ " ccccccccccccccccccccccccc) {\n}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
+ " ccccccccccccccccccccccccc) {\n}");
+
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
+ " ccccccccccccccccccccccccc) {\n}");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
+ " ccccccccccccccccccccccccc) {\n}");
+
+ verifyFormat(
+ "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
+ " ccccccccccccccccccccccccc) {\n}");
+ verifyFormat(
+ "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
+ " ccccccccccccccccccccccccc) {\n}");
+
+ verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
+ " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
+ " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
+ " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
+ verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
+ " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
+ " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
+ " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
+
+ verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
+ " aaaaaaaaaaaaaaa != aa) {\n}");
+ verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
+ " aaaaaaaaaaaaaaa != aa) {\n}");
+}
+
+TEST_F(FormatTest, BreaksAfterAssignments) {
+ verifyFormat(
+ "unsigned Cost =\n"
+ " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
+ " SI->getPointerAddressSpaceee());");
+ verifyFormat(
+ "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
+ " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
+
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("unsigned OriginalStartColumn =\n"
+ " SourceMgr.getSpellingColumnNumber(\n"
+ " Current.FormatTok.getStartOfNonWhitespace()) -\n"
+ " 1;");
+}
+
+TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
+ Style);
+
+ Style.PenaltyBreakAssignment = 20;
+ verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
+ " cccccccccccccccccccccccccc;",
+ Style);
+}
+
+TEST_F(FormatTest, AlignsAfterAssignments) {
+ verifyFormat(
+ "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa;");
+}
+
+TEST_F(FormatTest, AlignsAfterReturn) {
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
+ " aaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat(
+ "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
+ " aaaaaaaaaaaaaaaaaaaaaa());");
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("return\n"
+ " // true if code is one of a or b.\n"
+ " code == a || code == b;");
+}
+
+TEST_F(FormatTest, BreaksConditionalExpressions) {
+ verifyFormat(
+ "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
+ " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
+ " : aaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa);");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaa;");
+ verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
+ " aaaaaaaaa\n"
+ " ? b\n"
+ " : c);");
+ verifyFormat("return aaaa == bbbb\n"
+ " // comment\n"
+ " ? aaaa\n"
+ " : bbbb;");
+ verifyFormat("unsigned Indent =\n"
+ " format(TheLine.First,\n"
+ " IndentForLevel[TheLine.Level] >= 0\n"
+ " ? IndentForLevel[TheLine.Level]\n"
+ " : TheLine * 2,\n"
+ " TheLine.InPPDirective, PreviousEndOfLineColumn);",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
+ " ? aaaaaaaaaaaaaaa\n"
+ " : bbbbbbbbbbbbbbb //\n"
+ " ? ccccccccccccccc\n"
+ " : ddddddddddddddd;");
+ verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
+ " ? aaaaaaaaaaaaaaa\n"
+ " : (bbbbbbbbbbbbbbb //\n"
+ " ? ccccccccccccccc\n"
+ " : ddddddddddddddd);");
+ verifyFormat(
+ "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaa +\n"
+ " aaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaa;");
+ verifyFormat(
+ "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackArguments = false;
+ verifyFormat(
+ "void f() {\n"
+ " g(aaa,\n"
+ " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaa\n"
+ " : aaaaaaaaaaaaaaa);\n"
+ "}",
+ NoBinPacking);
+ verifyFormat(
+ "void f() {\n"
+ " g(aaa,\n"
+ " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ?: aaaaaaaaaaaaaaa);\n"
+ "}",
+ NoBinPacking);
+
+ verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
+ " // comment.\n"
+ " ccccccccccccccccccccccccccccccccccccccc\n"
+ " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
+
+ // Assignments in conditional expressions. Apparently not uncommon :-(.
+ verifyFormat("return a != b\n"
+ " // comment\n"
+ " ? a = b\n"
+ " : a = b;");
+ verifyFormat("return a != b\n"
+ " // comment\n"
+ " ? a = a != b\n"
+ " // comment\n"
+ " ? a = b\n"
+ " : a\n"
+ " : a;");
+ verifyFormat("return a != b\n"
+ " // comment\n"
+ " ? a\n"
+ " : a = a != b\n"
+ " // comment\n"
+ " ? a = b\n"
+ " : a;");
+
+ // Chained conditionals
+ FormatStyle Style = getLLVMStyleWithColumns(70);
+ Style.AlignOperands = FormatStyle::OAS_Align;
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 222222\n"
+ " : 333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : cccccccccccccc ? 3333333333333333\n"
+ " : 4444444444444444;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : (aaa ? bbb : ccc);",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccccc)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccccc)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : dddddddddddddddddd)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : dddddddddddddddddd)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : dddddddddddddddddd)",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccccc);",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : ccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : ccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee)\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccccc\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee\n"
+ " : bbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
+ " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee)\n"
+ " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
+ " : cccccccccccccccc ? dddddddddddddddddd\n"
+ " : eeeeeeeeeeeeeeeeee\n"
+ " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
+ " : 3333333333333333;",
+ Style);
+
+ Style.AlignOperands = FormatStyle::OAS_DontAlign;
+ Style.BreakBeforeTernaryOperators = false;
+ // FIXME: Aligning the question marks is weird given DontAlign.
+ // Consider disabling this alignment in this case. Also check whether this
+ // will render the adjustment from https://reviews.llvm.org/D82199
+ // unnecessary.
+ verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
+ " bbbb ? cccccccccccccccccc :\n"
+ " ddddd;",
+ Style);
+
+ verifyFormat(
+ "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
+ " /*\n"
+ " */\n"
+ " function() {\n"
+ " try {\n"
+ " return JJJJJJJJJJJJJJ(\n"
+ " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
+ " }\n"
+ " } :\n"
+ " function() {};",
+ "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
+ " /*\n"
+ " */\n"
+ " function() {\n"
+ " try {\n"
+ " return JJJJJJJJJJJJJJ(\n"
+ " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
+ " }\n"
+ " } :\n"
+ " function() {};",
+ getGoogleStyle(FormatStyle::LK_JavaScript));
+}
+
+TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
+ FormatStyle Style = getLLVMStyleWithColumns(70);
+ Style.BreakBeforeTernaryOperators = false;
+ verifyFormat(
+ "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
+ " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
+ " aaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa);",
+ Style);
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaa :\n"
+ " aaaaaaaaaaaaaaa;",
+ Style);
+ verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
+ " aaaaaaaaa ?\n"
+ " b :\n"
+ " c);",
+ Style);
+ verifyFormat("unsigned Indent =\n"
+ " format(TheLine.First,\n"
+ " IndentForLevel[TheLine.Level] >= 0 ?\n"
+ " IndentForLevel[TheLine.Level] :\n"
+ " TheLine * 2,\n"
+ " TheLine.InPPDirective, PreviousEndOfLineColumn);",
+ Style);
+ verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
+ " aaaaaaaaaaaaaaa :\n"
+ " bbbbbbbbbbbbbbb ? //\n"
+ " ccccccccccccccc :\n"
+ " ddddddddddddddd;",
+ Style);
+ verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
+ " aaaaaaaaaaaaaaa :\n"
+ " (bbbbbbbbbbbbbbb ? //\n"
+ " ccccccccccccccc :\n"
+ " ddddddddddddddd);",
+ Style);
+ verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
+ " ccccccccccccccccccccccccccc;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaa :\n"
+ " bbbbbbbbbbbbbbb + cccccccccccccccc;",
+ Style);
+
+ // Chained conditionals
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 222222 :\n"
+ " 333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " cccccccccccccccc ? 3333333333333333 :\n"
+ " 4444444444444444;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " (aaa ? bbb : ccc);",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " dddddddddddddddddd) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " dddddddddddddddddd) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " dddddddddddddddddd)",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc);",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " ccccccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " ccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " ccccccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee) :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee :\n"
+ " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
+ " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee) :\n"
+ " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
+ " cccccccccccccccccccc ? dddddddddddddddddd :\n"
+ " eeeeeeeeeeeeeeeeee :\n"
+ " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
+ " 3333333333333333;",
+ Style);
+}
+
+TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
+ verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
+ " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
+ verifyFormat("bool a = true, b = false;");
+
+ verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
+ verifyFormat(
+ "bool aaaaaaaaaaaaaaaaaaaaa =\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
+ " d = e && f;");
+ verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
+ " c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
+ verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
+ " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
+ verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
+ " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
+
+ FormatStyle Style = getGoogleStyle();
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ Style.DerivePointerAlignment = false;
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
+ " *b = bbbbbbbbbbbbbbbbbbb;",
+ Style);
+ verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
+ " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
+ Style);
+ verifyFormat("vector<int*> a, b;", Style);
+ verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
+ verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
+ verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style);
+ verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}",
+ Style);
+ verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}",
+ Style);
+ verifyFormat(
+ "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}",
+ Style);
+
+ verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
+ verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
+ verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
+ verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
+ verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}",
+ Style);
+}
+
+TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
+ verifyFormat("arr[foo ? bar : baz];");
+ verifyFormat("f()[foo ? bar : baz];");
+ verifyFormat("(a + b)[foo ? bar : baz];");
+ verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
+}
+
+TEST_F(FormatTest, AlignsStringLiterals) {
+ verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
+ " \"short literal\");");
+ verifyFormat(
+ "looooooooooooooooooooooooongFunction(\n"
+ " \"short literal\"\n"
+ " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
+ verifyFormat("someFunction(\"Always break between multi-line\"\n"
+ " \" string literals\",\n"
+ " also, other, parameters);");
+ verifyFormat("fun + \"1243\" /* comment */\n"
+ " \"5678\";",
+ "fun + \"1243\" /* comment */\n"
+ " \"5678\";",
+ getLLVMStyleWithColumns(28));
+ verifyFormat(
+ "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
+ " \"aaaaaaaaaaaaaaaaaaaaa\"\n"
+ " \"aaaaaaaaaaaaaaaa\";",
+ "aaaaaa ="
+ "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaa\" "
+ "\"aaaaaaaaaaaaaaaa\";");
+ verifyFormat("a = a + \"a\"\n"
+ " \"a\"\n"
+ " \"a\";");
+ verifyFormat("f(\"a\", \"b\"\n"
+ " \"c\");");
+
+ verifyFormat(
+ "#define LL_FORMAT \"ll\"\n"
+ "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
+ " \"d, ddddddddd: %\" LL_FORMAT \"d\");");
+
+ verifyFormat("#define A(X) \\\n"
+ " \"aaaaa\" #X \"bbbbbb\" \\\n"
+ " \"ccccc\"",
+ getLLVMStyleWithColumns(23));
+ verifyFormat("#define A \"def\"\n"
+ "f(\"abc\" A \"ghi\"\n"
+ " \"jkl\");");
+
+ verifyFormat("f(L\"a\"\n"
+ " L\"b\");");
+ verifyFormat("#define A(X) \\\n"
+ " L\"aaaaa\" #X L\"bbbbbb\" \\\n"
+ " L\"ccccc\"",
+ getLLVMStyleWithColumns(25));
+
+ verifyFormat("f(@\"a\"\n"
+ " @\"b\");");
+ verifyFormat("NSString s = @\"a\"\n"
+ " @\"b\"\n"
+ " @\"c\";");
+ verifyFormat("NSString s = @\"a\"\n"
+ " \"b\"\n"
+ " \"c\";");
+}
+
+TEST_F(FormatTest, ReturnTypeBreakingStyle) {
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 60;
+
+ // No declarations or definitions should be moved to own line.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_None;
+ verifyFormat("class A {\n"
+ " int f() { return 1; }\n"
+ " int g();\n"
+ " long\n"
+ " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
+ "};\n"
+ "int f() { return 1; }\n"
+ "int g();\n"
+ "int foooooooooooooooooooooooooooo::\n"
+ " baaaaaaaaaaaaaaaaaaaaar();",
+ Style);
+
+ // It is now allowed to break after a short return type if necessary.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_Automatic;
+ verifyFormat("class A {\n"
+ " int f() { return 1; }\n"
+ " int g();\n"
+ " long\n"
+ " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
+ "};\n"
+ "int f() { return 1; }\n"
+ "int g();\n"
+ "int\n"
+ "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
+ Style);
+
+ // It now must never break after a short return type.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_ExceptShortType;
+ verifyFormat("class A {\n"
+ " int f() { return 1; }\n"
+ " int g();\n"
+ " long foooooooooooooooooooooooooooo::\n"
+ " baaaaaaaaaaaaaaaaaaaar();\n"
+ "};\n"
+ "int f() { return 1; }\n"
+ "int g();\n"
+ "int foooooooooooooooooooooooooooo::\n"
+ " baaaaaaaaaaaaaaaaaaaaar();",
+ Style);
+
+ // All declarations and definitions should have the return type moved to its
+ // own line.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_All;
+ Style.TypenameMacros = {"LIST"};
+ verifyFormat("SomeType\n"
+ "funcdecl(LIST(uint64_t));",
+ Style);
+ verifyFormat("class E {\n"
+ " int\n"
+ " f() {\n"
+ " return 1;\n"
+ " }\n"
+ " int\n"
+ " g();\n"
+ " long\n"
+ " foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaar();\n"
+ "};\n"
+ "int\n"
+ "f() {\n"
+ " return 1;\n"
+ "}\n"
+ "int\n"
+ "g();\n"
+ "int\n"
+ "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
+ Style);
+
+ // Top-level definitions, and no kinds of declarations should have the
+ // return type moved to its own line.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
+ verifyFormat("class B {\n"
+ " int f() { return 1; }\n"
+ " int g();\n"
+ "};\n"
+ "int\n"
+ "f() {\n"
+ " return 1;\n"
+ "}\n"
+ "int g();",
+ Style);
+
+ // Top-level definitions and declarations should have the return type moved
+ // to its own line.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
+ verifyFormat("class C {\n"
+ " int f() { return 1; }\n"
+ " int g();\n"
+ "};\n"
+ "int\n"
+ "f() {\n"
+ " return 1;\n"
+ "}\n"
+ "int\n"
+ "g();\n"
+ "int\n"
+ "foooooooooooooooooooooooooooo::baaaaaaaaaaaaaaaaaaaaar();",
+ Style);
+
+ // All definitions should have the return type moved to its own line, but no
+ // kinds of declarations.
+ Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
+ verifyFormat("class D {\n"
+ " int\n"
+ " f() {\n"
+ " return 1;\n"
+ " }\n"
+ " int g();\n"
+ "};\n"
+ "int\n"
+ "f() {\n"
+ " return 1;\n"
+ "}\n"
+ "int g();",
+ Style);
+ verifyFormat("const char *\n"
+ "f(void) {\n" // Break here.
+ " return \"\";\n"
+ "}\n"
+ "const char *bar(void);", // No break here.
+ Style);
+ verifyFormat("template <class T>\n"
+ "T *\n"
+ "f(T &c) {\n" // Break here.
+ " return NULL;\n"
+ "}\n"
+ "template <class T> T *f(T &c);", // No break here.
+ Style);
+ verifyFormat("class C {\n"
+ " int\n"
+ " operator+() {\n"
+ " return 1;\n"
+ " }\n"
+ " int\n"
+ " operator()() {\n"
+ " return 1;\n"
+ " }\n"
+ "};",
+ Style);
+ verifyFormat("void\n"
+ "A::operator()() {}\n"
+ "void\n"
+ "A::operator>>() {}\n"
+ "void\n"
+ "A::operator+() {}\n"
+ "void\n"
+ "A::operator*() {}\n"
+ "void\n"
+ "A::operator->() {}\n"
+ "void\n"
+ "A::operator&() {}\n"
+ "void\n"
+ "A::operator&&() {}\n"
+ "void\n"
+ "A::operator[]() {}\n"
+ "void\n"
+ "A::operator!() {}\n"
+ "void\n"
+ "A::operator<Foo> *() {}\n"
+ "void\n"
+ "A::operator<Foo> &() {}\n",
+ Style);
+ verifyFormat("constexpr auto\n"
+ "operator()() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator>>() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator+() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator*() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator->() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator++() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator void *() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator void **() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator void *() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator void &() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator&&() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator char *() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator!() const -> reference {}\n"
+ "constexpr auto\n"
+ "operator[]() const -> reference {}",
+ Style);
+ verifyFormat("void *operator new(std::size_t s);", // No break here.
+ Style);
+ verifyFormat("void *\n"
+ "operator new(std::size_t s) {}",
+ Style);
+ verifyFormat("void *\n"
+ "operator delete[](void *ptr) {}",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
+ verifyFormat("const char *\n"
+ "f(void)\n" // Break here.
+ "{\n"
+ " return \"\";\n"
+ "}\n"
+ "const char *bar(void);", // No break here.
+ Style);
+ verifyFormat("template <class T>\n"
+ "T *\n" // Problem here: no line break
+ "f(T &c)\n" // Break here.
+ "{\n"
+ " return NULL;\n"
+ "}\n"
+ "template <class T> T *f(T &c);", // No break here.
+ Style);
+ verifyFormat("int\n"
+ "foo(A<bool> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("int\n"
+ "foo(A<8> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("int\n"
+ "foo(A<B<bool>, 8> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("int\n"
+ "foo(A<B<8>, bool> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("int\n"
+ "foo(A<B<bool>, bool> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("int\n"
+ "foo(A<B<8>, 8> a)\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ verifyFormat("int f(i);\n" // No break here.
+ "int\n" // Break here.
+ "f(i)\n"
+ "{\n"
+ " return i + 1;\n"
+ "}\n"
+ "int\n" // Break here.
+ "f(i)\n"
+ "{\n"
+ " return i + 1;\n"
+ "};",
+ Style);
+ verifyFormat("int f(a, b, c);\n" // No break here.
+ "int\n" // Break here.
+ "f(a, b, c)\n" // Break here.
+ "short a, b;\n"
+ "float c;\n"
+ "{\n"
+ " return a + b < c;\n"
+ "}\n"
+ "int\n" // Break here.
+ "f(a, b, c)\n" // Break here.
+ "short a, b;\n"
+ "float c;\n"
+ "{\n"
+ " return a + b < c;\n"
+ "};",
+ Style);
+ verifyFormat("byte *\n" // Break here.
+ "f(a)\n" // Break here.
+ "byte a[];\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style);
+ verifyFormat("byte *\n"
+ "f(a)\n"
+ "byte /* K&R C */ a[];\n"
+ "{\n"
+ " return a;\n"
+ "}\n"
+ "byte *\n"
+ "g(p)\n"
+ "byte /* K&R C */ *p;\n"
+ "{\n"
+ " return p;\n"
+ "}",
+ Style);
+ verifyFormat("bool f(int a, int) override;\n"
+ "Bar g(int a, Bar) final;\n"
+ "Bar h(a, Bar) final;",
+ Style);
+ verifyFormat("int\n"
+ "f(a)",
+ Style);
+ verifyFormat("bool\n"
+ "f(size_t = 0, bool b = false)\n"
+ "{\n"
+ " return !b;\n"
+ "}",
+ Style);
+
+ // The return breaking style doesn't affect:
+ // * function and object definitions with attribute-like macros
+ verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
+ " ABSL_GUARDED_BY(mutex) = {};",
+ getGoogleStyleWithColumns(40));
+ verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
+ " ABSL_GUARDED_BY(mutex); // comment",
+ getGoogleStyleWithColumns(40));
+ verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
+ " ABSL_GUARDED_BY(mutex1)\n"
+ " ABSL_GUARDED_BY(mutex2);",
+ getGoogleStyleWithColumns(40));
+ verifyFormat("Tttttt f(int a, int b)\n"
+ " ABSL_GUARDED_BY(mutex1)\n"
+ " ABSL_GUARDED_BY(mutex2);",
+ getGoogleStyleWithColumns(40));
+ // * typedefs
+ verifyGoogleFormat("typedef ATTR(X) char x;");
+
+ Style = getGNUStyle();
+
+ // Test for comments at the end of function declarations.
+ verifyFormat("void\n"
+ "foo (int a, /*abc*/ int b) // def\n"
+ "{\n"
+ "}",
+ Style);
+
+ verifyFormat("void\n"
+ "foo (int a, /* abc */ int b) /* def */\n"
+ "{\n"
+ "}",
+ Style);
+
+ // Definitions that should not break after return type
+ verifyFormat("void foo (int a, int b); // def", Style);
+ verifyFormat("void foo (int a, int b); /* def */", Style);
+ verifyFormat("void foo (int a, int b);", Style);
+}
+
+TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
+ FormatStyle NoBreak = getLLVMStyle();
+ NoBreak.AlwaysBreakBeforeMultilineStrings = false;
+ FormatStyle Break = getLLVMStyle();
+ Break.AlwaysBreakBeforeMultilineStrings = true;
+ verifyFormat("aaaa = \"bbbb\"\n"
+ " \"cccc\";",
+ NoBreak);
+ verifyFormat("aaaa =\n"
+ " \"bbbb\"\n"
+ " \"cccc\";",
+ Break);
+ verifyFormat("aaaa(\"bbbb\"\n"
+ " \"cccc\");",
+ NoBreak);
+ verifyFormat("aaaa(\n"
+ " \"bbbb\"\n"
+ " \"cccc\");",
+ Break);
+ verifyFormat("aaaa(qqq, \"bbbb\"\n"
+ " \"cccc\");",
+ NoBreak);
+ verifyFormat("aaaa(qqq,\n"
+ " \"bbbb\"\n"
+ " \"cccc\");",
+ Break);
+ verifyFormat("aaaa(qqq,\n"
+ " L\"bbbb\"\n"
+ " L\"cccc\");",
+ Break);
+ verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
+ " \"bbbb\"));",
+ Break);
+ verifyFormat("string s = someFunction(\n"
+ " \"abc\"\n"
+ " \"abc\");",
+ Break);
+
+ // As we break before unary operators, breaking right after them is bad.
+ verifyFormat("string foo = abc ? \"x\"\n"
+ " \"blah blah blah blah blah blah\"\n"
+ " : \"y\";",
+ Break);
+
+ // Don't break if there is no column gain.
+ verifyFormat("f(\"aaaa\"\n"
+ " \"bbbb\");",
+ Break);
+
+ // Treat literals with escaped newlines like multi-line string literals.
+ verifyNoChange("x = \"a\\\n"
+ "b\\\n"
+ "c\";",
+ NoBreak);
+ verifyFormat("xxxx =\n"
+ " \"a\\\n"
+ "b\\\n"
+ "c\";",
+ "xxxx = \"a\\\n"
+ "b\\\n"
+ "c\";",
+ Break);
+
+ verifyFormat("NSString *const kString =\n"
+ " @\"aaaa\"\n"
+ " @\"bbbb\";",
+ "NSString *const kString = @\"aaaa\"\n"
+ "@\"bbbb\";",
+ Break);
+
+ Break.ColumnLimit = 0;
+ verifyFormat("const char *hello = \"hello llvm\";", Break);
+}
+
+TEST_F(FormatTest, AlignsPipes) {
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
+ " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
+ " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
+ verifyFormat(
+ "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
+ verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
+ verifyFormat(
+ "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("LOG_IF(aaa == //\n"
+ " bbb)\n"
+ " << a << b;");
+
+ // But sometimes, breaking before the first "<<" is desirable.
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
+ " << BEF << IsTemplate << Description << E->getType();");
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " << aaa;");
+
+ verifyFormat(
+ "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+
+ // Incomplete string literal.
+ verifyFormat("llvm::errs() << \"\n"
+ " << a;",
+ "llvm::errs() << \"\n<<a;");
+
+ verifyFormat("void f() {\n"
+ " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
+ " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
+ "}");
+
+ // Handle 'endl'.
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
+ " << bbbbbbbbbbbbbbbbbbbbbb << endl;");
+ verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
+
+ // Handle '\n'.
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
+ " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
+ " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
+ verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
+ " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
+ verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
+}
+
+TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
+ verifyFormat("return out << \"somepacket = {\\n\"\n"
+ " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
+ " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
+ " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
+ " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
+ " << \"}\";");
+
+ verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
+ " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
+ " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
+ " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
+ " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
+ verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
+ " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
+ verifyFormat(
+ "void f() {\n"
+ " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
+ "}");
+
+ // Breaking before the first "<<" is generally not desirable.
+ verifyFormat(
+ "llvm::errs()\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ getLLVMStyleWithColumns(70));
+ verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ getLLVMStyleWithColumns(70));
+
+ verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
+ " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
+ " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
+ verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
+ " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
+ " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
+ verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
+ " (aaaa + aaaa);",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
+ " (aaaaaaa + aaaaa));",
+ getLLVMStyleWithColumns(40));
+ verifyFormat(
+ "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
+ " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
+ " bbbbbbbbbbbbbbbbbbbbbbb);");
+}
+
+TEST_F(FormatTest, WrapBeforeInsertionOperatorbetweenStringLiterals) {
+ verifyFormat("QStringList() << \"foo\" << \"bar\";");
+
+ verifyNoChange("QStringList() << \"foo\"\n"
+ " << \"bar\";");
+
+ verifyFormat("log_error(log, \"foo\" << \"bar\");",
+ "log_error(log, \"foo\"\n"
+ " << \"bar\");");
+}
+
+TEST_F(FormatTest, UnderstandsEquals) {
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat(
+ "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
+ verifyFormat(
+ "if (a) {\n"
+ " f();\n"
+ "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+ "}");
+
+ verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " 100000000 + 10000000) {\n}");
+}
+
+TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
+ " .looooooooooooooooooooooooooooooooooooooongFunction();");
+
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
+ " ->looooooooooooooooooooooooooooooooooooooongFunction();");
+
+ verifyFormat(
+ "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
+ " Parameter2);");
+
+ verifyFormat(
+ "ShortObject->shortFunction(\n"
+ " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
+ " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
+
+ verifyFormat("loooooooooooooongFunction(\n"
+ " LoooooooooooooongObject->looooooooooooooooongFunction());");
+
+ verifyFormat(
+ "function(LoooooooooooooooooooooooooooooooooooongObject\n"
+ " ->loooooooooooooooooooooooooooooooooooooooongFunction());");
+
+ verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
+ " .WillRepeatedly(Return(SomeValue));");
+ verifyFormat("void f() {\n"
+ " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
+ " .Times(2)\n"
+ " .WillRepeatedly(Return(SomeValue));\n"
+ "}");
+ verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
+ " ccccccccccccccccccccccc);");
+ verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaa(aaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("void f() {\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
+ "}");
+ verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
+ "}");
+
+ // Here, it is not necessary to wrap at "." or "->".
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
+ " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
+ verifyFormat(
+ "aaaaaaaaaaa->aaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));");
+
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
+ verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
+ " aaaaaaaaa()->aaaaaa()->aaaaa());");
+ verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
+ " aaaaaaaaa()->aaaaaa()->aaaaa());");
+
+ verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .a();");
+
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ NoBinPacking);
+
+ // If there is a subsequent call, change to hanging indentation.
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
+ verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
+}
+
+TEST_F(FormatTest, WrapsTemplateDeclarations) {
+ verifyFormat("template <typename T>\n"
+ "virtual void loooooooooooongFunction(int Param1, int Param2);");
+ verifyFormat("template <typename T>\n"
+ "// T should be one of {A, B}.\n"
+ "virtual void loooooooooooongFunction(int Param1, int Param2);");
+ verifyFormat(
+ "template <typename T>\n"
+ "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
+ verifyFormat("template <typename T>\n"
+ "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
+ " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
+ verifyFormat(
+ "template <typename T>\n"
+ "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
+ " int Paaaaaaaaaaaaaaaaaaaaram2);");
+ verifyFormat(
+ "template <typename T>\n"
+ "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("template <typename T>\n"
+ "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat(
+ "template <typename T1, typename T2 = char, typename T3 = char,\n"
+ " typename T4 = char>\n"
+ "void f();");
+ verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
+ " template <typename> class cccccccccccccccccccccc,\n"
+ " typename ddddddddddddd>\n"
+ "class C {};");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("void f() {\n"
+ " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
+ " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
+ "}");
+
+ verifyFormat("template <typename T> class C {};");
+ verifyFormat("template <typename T> void f();");
+ verifyFormat("template <typename T> void f() {}");
+ verifyFormat(
+ "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
+ " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbb);",
+ getLLVMStyleWithColumns(72));
+ verifyFormat("static_cast<A< //\n"
+ " B> *>(\n"
+ "\n"
+ ");",
+ "static_cast<A<//\n"
+ " B>*>(\n"
+ "\n"
+ " );");
+ verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
+
+ FormatStyle AlwaysBreak = getLLVMStyle();
+ AlwaysBreak.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+ verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
+ verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
+ verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
+ verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
+ " ccccccccccccccccccccccccccccccccccccccccccccccc);");
+ verifyFormat("template <template <typename> class Fooooooo,\n"
+ " template <typename> class Baaaaaaar>\n"
+ "struct C {};",
+ AlwaysBreak);
+ verifyFormat("template <typename T> // T can be A, B or C.\n"
+ "struct C {};",
+ AlwaysBreak);
+ verifyFormat("template <typename T>\n"
+ "C(T) noexcept;",
+ AlwaysBreak);
+ verifyFormat("template <typename T>\n"
+ "ClassName(T) noexcept;",
+ AlwaysBreak);
+ verifyFormat("template <typename T>\n"
+ "POOR_NAME(T) noexcept;",
+ AlwaysBreak);
+ verifyFormat("template <enum E> class A {\n"
+ "public:\n"
+ " E *f();\n"
+ "};");
+
+ FormatStyle NeverBreak = getLLVMStyle();
+ NeverBreak.BreakTemplateDeclarations = FormatStyle::BTDS_No;
+ verifyFormat("template <typename T> class C {};", NeverBreak);
+ verifyFormat("template <typename T> void f();", NeverBreak);
+ verifyFormat("template <typename T> void f() {}", NeverBreak);
+ verifyFormat("template <typename T> C(T) noexcept;", NeverBreak);
+ verifyFormat("template <typename T> ClassName(T) noexcept;", NeverBreak);
+ verifyFormat("template <typename T> POOR_NAME(T) noexcept;", NeverBreak);
+ verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "bbbbbbbbbbbbbbbbbbbb) {}",
+ NeverBreak);
+ verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
+ " ccccccccccccccccccccccccccccccccccccccccccccccc);",
+ NeverBreak);
+ verifyFormat("template <template <typename> class Fooooooo,\n"
+ " template <typename> class Baaaaaaar>\n"
+ "struct C {};",
+ NeverBreak);
+ verifyFormat("template <typename T> // T can be A, B or C.\n"
+ "struct C {};",
+ NeverBreak);
+ verifyFormat("template <enum E> class A {\n"
+ "public:\n"
+ " E *f();\n"
+ "};",
+ NeverBreak);
+ NeverBreak.PenaltyBreakTemplateDeclaration = 100;
+ verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "bbbbbbbbbbbbbbbbbbbb) {}",
+ NeverBreak);
+
+ auto Style = getLLVMStyle();
+ Style.BreakTemplateDeclarations = FormatStyle::BTDS_Leave;
+
+ verifyNoChange("template <typename T>\n"
+ "class C {};",
+ Style);
+ verifyFormat("template <typename T> class C {};", Style);
+
+ verifyNoChange("template <typename T>\n"
+ "void f();",
+ Style);
+ verifyFormat("template <typename T> void f();", Style);
+
+ verifyNoChange("template <typename T>\n"
+ "void f() {}",
+ Style);
+ verifyFormat("template <typename T> void f() {}", Style);
+
+ verifyNoChange("template <typename T>\n"
+ "// T can be A, B or C.\n"
+ "struct C {};",
+ Style);
+ verifyFormat("template <typename T> // T can be A, B or C.\n"
+ "struct C {};",
+ Style);
+
+ verifyNoChange("template <typename T>\n"
+ "C(T) noexcept;",
+ Style);
+ verifyFormat("template <typename T> C(T) noexcept;", Style);
+
+ verifyNoChange("template <enum E>\n"
+ "class A {\n"
+ "public:\n"
+ " E *f();\n"
+ "};",
+ Style);
+ verifyFormat("template <enum E> class A {\n"
+ "public:\n"
+ " E *f();\n"
+ "};",
+ Style);
+
+ verifyNoChange("template <auto x>\n"
+ "constexpr int simple(int) {\n"
+ " char c;\n"
+ " return 1;\n"
+ "}",
+ Style);
+ verifyFormat("template <auto x> constexpr int simple(int) {\n"
+ " char c;\n"
+ " return 1;\n"
+ "}",
+ Style);
+
+ Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
+ verifyNoChange("template <auto x>\n"
+ "requires(x > 1)\n"
+ "constexpr int with_req(int) {\n"
+ " return 1;\n"
+ "}",
+ Style);
+ verifyFormat("template <auto x> requires(x > 1)\n"
+ "constexpr int with_req(int) {\n"
+ " return 1;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
+ FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+ Style.ColumnLimit = 60;
+ verifyFormat("// Baseline - no comments.\n"
+ "template <\n"
+ " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
+ "void f() {}",
+ Style);
+
+ verifyFormat("template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
+ "void f() {}",
+ "template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
+ "void f() {}",
+ Style);
+
+ verifyFormat(
+ "template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
+ "void f() {}",
+ "template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
+ "void f() {}",
+ Style);
+
+ verifyFormat("template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
+ " // multiline\n"
+ "void f() {}",
+ "template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
+ " // multiline\n"
+ "void f() {}",
+ Style);
+
+ verifyFormat(
+ "template <typename aaaaaaaaaa<\n"
+ " bbbbbbbbbbbb>::value> // trailing loooong\n"
+ "void f() {}",
+ "template <\n"
+ " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
+ "void f() {}",
+ Style);
+}
+
+TEST_F(FormatTest, BreakBeforeTemplateCloser) {
+ auto Style = getLLVMStyle();
+ // Begin with tests covering the case where there is no constraint on the
+ // column limit.
+ Style.ColumnLimit = 0;
+ Style.BreakBeforeTemplateCloser = true;
+ // BreakBeforeTemplateCloser should NOT force template declarations onto
+ // multiple lines.
+ verifyFormat("template <typename Foo>\n"
+ "void foo() {}",
+ Style);
+ verifyFormat("template <typename Foo, typename Bar>\n"
+ "void foo() {}",
+ Style);
+ // It should add a line break before > if not already present:
+ verifyFormat("template <\n"
+ " typename Foo\n"
+ ">\n"
+ "void foo() {}",
+ "template <\n"
+ " typename Foo>\n"
+ "void foo() {}",
+ Style);
+ verifyFormat("template <\n"
+ " typename Foo,\n"
+ " typename Bar\n"
+ ">\n"
+ "void foo() {}",
+ "template <\n"
+ " typename Foo,\n"
+ " typename Bar>\n"
+ "void foo() {}",
+ Style);
+ // When within an indent scope, the > should be placed accordingly:
+ verifyFormat("struct Baz {\n"
+ " template <\n"
+ " typename Foo,\n"
+ " typename Bar\n"
+ " >\n"
+ " void foo() {}\n"
+ "};",
+ "struct Baz {\n"
+ " template <\n"
+ " typename Foo,\n"
+ " typename Bar>\n"
+ " void foo() {}\n"
+ "};",
+ Style);
+
+ // Test from https://github.com/llvm/llvm-project/issues/80049:
+ verifyFormat(
+ "using type = std::remove_cv_t<\n"
+ " add_common_cv_reference<\n"
+ " std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
+ " T0,\n"
+ " T1\n"
+ " >\n"
+ ">;",
+ "using type = std::remove_cv_t<\n"
+ " add_common_cv_reference<\n"
+ " std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
+ " T0,\n"
+ " T1>>;",
+ Style);
+
+ // Test lambda goes to next line:
+ verifyFormat("void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T\n"
+ " >(T t) {\n"
+ " };\n"
+ "}",
+ "void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T>(T t){\n"
+ " };\n"
+ "}",
+ Style);
+ // With no column limit, two parameters can go on the same line:
+ verifyFormat("void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T, typename Foo\n"
+ " >(T t) {\n"
+ " };\n"
+ "}",
+ "void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T, typename Foo>(T t){\n"
+ " };\n"
+ "}",
+ Style);
+ // Or on different lines:
+ verifyFormat("void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T,\n"
+ " typename Foo\n"
+ " >(T t) {\n"
+ " };\n"
+ "}",
+ "void foo() {\n"
+ " auto lambda = []<\n"
+ " typename T,\n"
+ " typename Foo>(T t){\n"
+ " };\n"
+ "}",
+ Style);
+
+ // Test template usage goes to next line too:
+ verifyFormat("void foo() {\n"
+ " myFunc<\n"
+ " T\n"
+ " >();\n"
+ "}",
+ "void foo() {\n"
+ " myFunc<\n"
+ " T>();\n"
+ "}",
+ Style);
+
+ // Now test that it handles the cases when the column limit forces wrapping.
+ Style.ColumnLimit = 40;
+ // The typename goes on the first line if it fits:
+ verifyFormat("template <typename Fooooooooooooooooooo,\n"
+ " typename Bar>\n"
+ "void foo() {}",
+ Style);
+ verifyFormat("template <typename Foo,\n"
+ " typename Barrrrrrrrrrrrrrrrrr>\n"
+ "void foo() {}",
+ Style);
+ // Long names should be split in one step:
+ verifyFormat("template <\n"
+ " typename Foo,\n"
+ " typename Barrrrrrrrrrrrrrrrrrr\n"
+ ">\n"
+ "void foo() {}",
+ "template <typename Foo, typename Barrrrrrrrrrrrrrrrrrr>\n"
+ "void foo() {}",
+ Style);
+ verifyFormat("template <\n"
+ " typename Foooooooooooooooooooo,\n"
+ " typename Bar\n"
+ ">\n"
+ "void foo() {}",
+ "template <typename Foooooooooooooooooooo, typename Bar>\n"
+ "void foo() {}",
+ Style);
+ // Even when there is only one long name:
+ verifyFormat("template <\n"
+ " typename Foooooooooooooooooooo\n"
+ ">\n"
+ "void foo() {}",
+ "template <typename Foooooooooooooooooooo>\n"
+ "void foo() {}",
+ Style);
+ // Test lambda goes to next line if the type is looong:
+ verifyFormat("void foo() {\n"
+ " auto lambda =\n"
+ " []<\n"
+ " typename Loooooooooooooooooooooooooooooooooong\n"
+ " >(T t) {};\n"
+ " auto lambda =\n"
+ " [looooooooooooooong]<\n"
+ " typename Loooooooooooooooooooooooooooooooooong\n"
+ " >(T t) {};\n"
+ " auto lambda =\n"
+ " []<\n"
+ " typename T,\n"
+ " typename Loooooooooooooooooooooooooooooooooong\n"
+ " >(T t) {};\n"
+ // Nested:
+ " auto lambda =\n"
+ " []<\n"
+ " template <typename, typename>\n"
+ " typename Looooooooooooooooooong\n"
+ " >(T t) {};\n"
+ // Same idea, the "T" is now short rather than Looong:
+ " auto lambda =\n"
+ " []<template <typename, typename>\n"
+ " typename T>(T t) {};\n"
+ // Nested with long capture forces the style to block indent:
+ " auto lambda =\n"
+ " [loooooooooooooooooooong]<\n"
+ " template <typename, typename>\n"
+ " typename Looooooooooooooooooong\n"
+ " >(T t) {};\n"
+ // But *now* it stays block indented even when T is short:
+ " auto lambda =\n"
+ " [loooooooooooooooooooong]<\n"
+ " template <typename, typename>\n"
+ " typename T\n"
+ " >(T t) {};\n"
+ // Nested, with long name and long captures:
+ " auto lambda =\n"
+ " [loooooooooooooooooooong]<\n"
+ " template <\n"
+ " typename Foooooooooooooooo,\n"
+ " typename\n"
+ " >\n"
+ " typename T\n"
+ " >(T t) {};\n"
+ // Allow the nested template to be on the same line:
+ " auto lambda =\n"
+ " [loooooooooooooooooooong]<\n"
+ " template <typename Fooooooooo,\n"
+ " typename>\n"
+ " typename T\n"
+ " >(T t) {};\n"
+ "}",
+ Style);
+
+ // Test template usage goes to next line if the type is looong:
+ verifyFormat("void foo() {\n"
+ " myFunc<\n"
+ " Looooooooooooooooooooooooong\n"
+ " >();\n"
+ "}",
+ Style);
+ // Even a single type in the middle is enough to force it to block indent
+ // style:
+ verifyFormat("void foo() {\n"
+ " myFunc<\n"
+ " Foo, Foo, Foo,\n"
+ " Foooooooooooooooooooooooooooooo,\n"
+ " Foo, Foo, Foo, Foo\n"
+ " >();\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, WrapsTemplateParameters) {
+ FormatStyle Style = getLLVMStyle();
+ Style.AlignAfterOpenBracket = false;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+ verifyFormat(
+ "template <typename... a> struct q {};\n"
+ "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
+ " y;",
+ Style);
+ Style.AlignAfterOpenBracket = false;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat(
+ "template <typename... a> struct r {};\n"
+ "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
+ " y;",
+ Style);
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+ verifyFormat("template <typename... a> struct s {};\n"
+ "extern s<\n"
+ " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
+ "aaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
+ "aaaaaaaaaaaaaaaaaaaaaa>\n"
+ " y;",
+ Style);
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat("template <typename... a> struct t {};\n"
+ "extern t<\n"
+ " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
+ "aaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
+ "aaaaaaaaaaaaaaaaaaaaaa>\n"
+ " y;",
+ Style);
+}
+
+TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
+
+ // FIXME: Should we have the extra indent after the second break?
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+
+ verifyFormat(
+ "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
+ " cccccccccccccccccccccccccccccccccccccccccccccc());");
+
+ // Breaking at nested name specifiers is generally not desirable.
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaa);",
+ getLLVMStyleWithColumns(74));
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
+
+ verifyFormat(
+ "LongClassNameToShowTheIssue::AndAnotherLongClassNameToShowTheIssue::\n"
+ " AndAnotherLongClassNameToShowTheIssue() {}\n"
+ "LongClassNameToShowTheIssue::AndAnotherLongClassNameToShowTheIssue::\n"
+ " ~AndAnotherLongClassNameToShowTheIssue() {}");
+}
+
+TEST_F(FormatTest, UnderstandsTemplateParameters) {
+ verifyFormat("A<int> a;");
+ verifyFormat("A<A<A<int>>> a;");
+ verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
+ verifyFormat("bool x = a < 1 || 2 > a;");
+ verifyFormat("bool x = 5 < f<int>();");
+ verifyFormat("bool x = f<int>() > 5;");
+ verifyFormat("bool x = 5 < a<int>::x;");
+ verifyFormat("bool x = a < 4 ? a > 2 : false;");
+ verifyFormat("bool x = f() ? a < 2 : a > 2;");
+
+ verifyGoogleFormat("A<A<int>> a;");
+ verifyGoogleFormat("A<A<A<int>>> a;");
+ verifyGoogleFormat("A<A<A<A<int>>>> a;");
+ verifyGoogleFormat("A<A<int> > a;");
+ verifyGoogleFormat("A<A<A<int> > > a;");
+ verifyGoogleFormat("A<A<A<A<int> > > > a;");
+ verifyGoogleFormat("A<::A<int>> a;");
+ verifyGoogleFormat("A<::A> a;");
+ verifyGoogleFormat("A< ::A> a;");
+ verifyGoogleFormat("A< ::A<int> > a;");
+ verifyFormat("A<A<A<A>>> a;", "A<A<A<A> >> a;", getGoogleStyle());
+ verifyFormat("A<A<A<A>>> a;", "A<A<A<A>> > a;", getGoogleStyle());
+ verifyFormat("A<::A<int>> a;", "A< ::A<int>> a;", getGoogleStyle());
+ verifyFormat("A<::A<int>> a;", "A<::A<int> > a;", getGoogleStyle());
+ verifyFormat("auto x = [] { A<A<A<A>>> a; };", "auto x=[]{A<A<A<A> >> a;};",
+ getGoogleStyle());
+
+ verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
+
+ // template closer followed by a token that starts with > or =
+ verifyFormat("bool b = a<1> > 1;");
+ verifyFormat("bool b = a<1> >= 1;");
+ verifyFormat("int i = a<1> >> 1;");
+ FormatStyle Style = getLLVMStyle();
+ Style.SpaceBeforeAssignmentOperators = false;
+ verifyFormat("bool b= a<1> == 1;", Style);
+ verifyFormat("a<int> = 1;", Style);
+ verifyFormat("a<int> >>= 1;", Style);
+
+ verifyFormat("test < a | b >> c;");
+ verifyFormat("test<test<a | b>> c;");
+ verifyFormat("test >> a >> b;");
+ verifyFormat("test << a >> b;");
+
+ verifyFormat("f<int>();");
+ verifyFormat("template <typename T> void f() {}");
+ verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
+ verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
+ "sizeof(char)>::type>;");
+ verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
+ verifyFormat("f(a.operator()<A>());");
+ verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .template operator()<A>());",
+ getLLVMStyleWithColumns(35));
+ verifyFormat("bool_constant<a && noexcept(f())>;");
+ verifyFormat("bool_constant<a || noexcept(f())>;");
+
+ verifyFormat("if (std::tuple_size_v<T> > 0)");
+
+ // Not template parameters.
+ verifyFormat("return a < b && c > d;");
+ verifyFormat("a < 0 ? b : a > 0 ? c : d;");
+ verifyFormat("ratio{-1, 2} < ratio{-1, 3} == -1 / 3 > -1 / 2;");
+ verifyFormat("void f() {\n"
+ " while (a < b && c > d) {\n"
+ " }\n"
+ "}");
+ verifyFormat("template <typename... Types>\n"
+ "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
+ verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
+ verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
+ verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
+
+ verifyFormat("#define FOO(typeName, realClass) \\\n"
+ " {#typeName, foo<FooType>(new foo<realClass>(#typeName))}",
+ getLLVMStyleWithColumns(60));
+}
+
+TEST_F(FormatTest, UnderstandsShiftOperators) {
+ verifyFormat("if (i < x >> 1)");
+ verifyFormat("while (i < x >> 1)");
+ verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
+ verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
+ verifyFormat(
+ "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
+ verifyFormat("Foo.call<Bar<Function>>()");
+ verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
+ verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
+ "++i, v = v >> 1)");
+ verifyFormat("if (w<u<v<x>>, 1>::t)");
+}
+
+TEST_F(FormatTest, BitshiftOperatorWidth) {
+ verifyFormat("int a = 1 << 2; /* foo\n"
+ " bar */",
+ "int a=1<<2; /* foo\n"
+ " bar */");
+
+ verifyFormat("int b = 256 >> 1; /* foo\n"
+ " bar */",
+ "int b =256>>1 ; /* foo\n"
+ " bar */");
+}
+
+TEST_F(FormatTest, UnderstandsBinaryOperators) {
+ verifyFormat("COMPARE(a, ==, b);");
+ verifyFormat("auto s = sizeof...(Ts) - 1;");
+}
+
+TEST_F(FormatTest, UnderstandsPointersToMembers) {
+ verifyFormat("int A::*x;");
+ verifyFormat("int (S::*func)(void *);");
+ verifyFormat("void f() { int (S::*func)(void *); }");
+ verifyFormat("typedef bool *(Class::*Member)() const;");
+ verifyFormat("void f() {\n"
+ " (a->*f)();\n"
+ " a->*x;\n"
+ " (a.*f)();\n"
+ " ((*a).*f)();\n"
+ " a.*x;\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
+ " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
+ "}");
+ verifyFormat(
+ "(aaaaaaaaaa->*bbbbbbb)(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
+
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
+ verifyFormat("typedef bool *(Class::*Member)() const;", Style);
+ verifyFormat("void f(int A::*p) { int A::*v = &A::B; }", Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("typedef bool* (Class::*Member)() const;", Style);
+ verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("typedef bool * (Class::*Member)() const;", Style);
+ verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
+}
+
+TEST_F(FormatTest, UnderstandsUnaryOperators) {
+ verifyFormat("int a = -2;");
+ verifyFormat("f(-1, -2, -3);");
+ verifyFormat("a[-1] = 5;");
+ verifyFormat("int a = 5 + -2;");
+ verifyFormat("if (i == -1) {\n}");
+ verifyFormat("if (i != -1) {\n}");
+ verifyFormat("if (i > -1) {\n}");
+ verifyFormat("if (i < -1) {\n}");
+ verifyFormat("++(a->f());");
+ verifyFormat("--(a->f());");
+ verifyFormat("(a->f())++;");
+ verifyFormat("a[42]++;");
+ verifyFormat("if (!(a->f())) {\n}");
+ verifyFormat("if (!+i) {\n}");
+ verifyFormat("~&a;");
+ verifyFormat("for (x = 0; -10 < x; --x) {\n}");
+ verifyFormat("sizeof -x");
+ verifyFormat("sizeof +x");
+ verifyFormat("sizeof *x");
+ verifyFormat("sizeof &x");
+ verifyFormat("delete +x;");
+ verifyFormat("co_await +x;");
+ verifyFormat("case *x:");
+ verifyFormat("case &x:");
+
+ verifyFormat("a-- > b;");
+ verifyFormat("b ? -a : c;");
+ verifyFormat("n * sizeof char16;");
+ verifyGoogleFormat("n * alignof char16;");
+ verifyFormat("sizeof(char);");
+ verifyGoogleFormat("alignof(char);");
+
+ verifyFormat("return -1;");
+ verifyFormat("throw -1;");
+ verifyFormat("switch (a) {\n"
+ "case -1:\n"
+ " break;\n"
+ "}");
+ verifyFormat("#define X -1");
+ verifyFormat("#define X -kConstant");
+
+ verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
+ verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
+
+ verifyFormat("int a = /* confusing comment */ -1;");
+ // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
+ verifyFormat("int a = i /* confusing comment */++;");
+
+ verifyFormat("co_yield -1;");
+ verifyFormat("co_return -1;");
+
+ // Check that * is not treated as a binary operator when we set
+ // PointerAlignment as PAS_Left after a keyword and not a declaration.
+ FormatStyle PASLeftStyle = getLLVMStyle();
+ PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("co_return *a;", PASLeftStyle);
+ verifyFormat("co_await *a;", PASLeftStyle);
+ verifyFormat("co_yield *a", PASLeftStyle);
+ verifyFormat("return *a;", PASLeftStyle);
+}
+
+TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
+ verifyFormat("if (!aaaaaaaaaa( // break\n"
+ " aaaaa)) {\n"
+ "}");
+ verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
+ " aaaaa));");
+ verifyFormat("*aaa = aaaaaaa( // break\n"
+ " bbbbbb);");
+}
+
+TEST_F(FormatTest, UnderstandsOverloadedOperators) {
+ verifyFormat("bool operator<();");
+ verifyFormat("bool operator>();");
+ verifyFormat("bool operator=();");
+ verifyFormat("bool operator==();");
+ verifyFormat("bool operator!=();");
+ verifyFormat("int operator+();");
+ verifyFormat("int operator++();");
+ verifyFormat("int operator++(int) volatile noexcept;");
+ verifyFormat("bool operator,();");
+ verifyFormat("bool operator();");
+ verifyFormat("bool operator()();");
+ verifyFormat("bool operator[]();");
+ verifyFormat("operator bool();");
+ verifyFormat("operator int();");
+ verifyFormat("operator void *();");
+ verifyFormat("operator SomeType<int>();");
+ verifyFormat("operator SomeType<int, int>();");
+ verifyFormat("operator SomeType<SomeType<int>>();");
+ verifyFormat("operator< <>();");
+ verifyFormat("operator<< <>();");
+ verifyFormat("< <>");
+
+ verifyFormat("void *operator new(std::size_t size);");
+ verifyFormat("void *operator new[](std::size_t size);");
+ verifyFormat("void operator delete(void *ptr);");
+ verifyFormat("void operator delete[](void *ptr);");
+ verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
+ "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
+ " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
+
+ verifyFormat(
+ "ostream &operator<<(ostream &OutputStream,\n"
+ " SomeReallyLongType WithSomeReallyLongValue);");
+ verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
+ " const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
+ " return left.group < right.group;\n"
+ "}");
+ verifyFormat("SomeType &operator=(const SomeType &S);");
+ verifyFormat("f.template operator()<int>();");
+
+ verifyGoogleFormat("operator void*();");
+ verifyGoogleFormat("operator SomeType<SomeType<int>>();");
+ verifyGoogleFormat("operator ::A();");
+
+ verifyFormat("using A::operator+;");
+ verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
+ "int i;");
+
+ // Calling an operator as a member function.
+ verifyFormat("void f() { a.operator*(); }");
+ verifyFormat("void f() { a.operator*(b & b); }");
+ verifyFormat("void f() { a->operator&(a * b); }");
+ verifyFormat("void f() { NS::a.operator+(*b * *b); }");
+ verifyFormat("void f() { operator*(a & a); }");
+ verifyFormat("void f() { operator&(a, b * b); }");
+
+ verifyFormat("void f() { return operator()(x) * b; }");
+ verifyFormat("void f() { return operator[](x) * b; }");
+ verifyFormat("void f() { return operator\"\"_a(x) * b; }");
+ verifyFormat("void f() { return operator\"\" _a(x) * b; }");
+ verifyFormat("void f() { return operator\"\"s(x) * b; }");
+ verifyFormat("void f() { return operator\"\" s(x) * b; }");
+ verifyFormat("void f() { return operator\"\"if(x) * b; }");
+
+ verifyFormat("::operator delete(foo);");
+ verifyFormat("::operator new(n * sizeof(foo));");
+ verifyFormat("foo() { ::operator delete(foo); }");
+ verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
+}
+
+TEST_F(FormatTest, SpaceBeforeTemplateCloser) {
+ verifyFormat("C<&operator- > minus;");
+ verifyFormat("C<&operator> > gt;");
+ verifyFormat("C<&operator>= > ge;");
+ verifyFormat("C<&operator<= > le;");
+ verifyFormat("C<&operator< <X>> lt;");
+}
+
+TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
+ verifyFormat("void A::b() && {}");
+ verifyFormat("void A::b() && noexcept {}");
+ verifyFormat("Deleted &operator=(const Deleted &) & = default;");
+ verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
+ verifyFormat("Deleted &operator=(const Deleted &) & noexcept = default;");
+ verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
+ verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
+ verifyFormat("Deleted &operator=(const Deleted &) &;");
+ verifyFormat("Deleted &operator=(const Deleted &) &&;");
+ verifyFormat("SomeType MemberFunction(const Deleted &) &;");
+ verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
+ verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
+ verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
+ verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
+ verifyFormat("SomeType MemberFunction(const Deleted &) && noexcept {}");
+ verifyFormat("void Fn(T const &) const &;");
+ verifyFormat("void Fn(T const volatile &&) const volatile &&;");
+ verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;");
+ verifyGoogleFormat("template <typename T>\n"
+ "void F(T) && = delete;");
+ verifyFormat("template <typename T> void operator=(T) &;");
+ verifyFormat("template <typename T> void operator=(T) const &;");
+ verifyFormat("template <typename T> void operator=(T) & noexcept;");
+ verifyFormat("template <typename T> void operator=(T) & = default;");
+ verifyFormat("template <typename T> void operator=(T) &&;");
+ verifyFormat("template <typename T> void operator=(T) && = delete;");
+ verifyFormat("template <typename T> void operator=(T) & {}");
+ verifyFormat("template <typename T> void operator=(T) && {}");
+
+ FormatStyle AlignLeft = getLLVMStyle();
+ AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("void A::b() && {}", AlignLeft);
+ verifyFormat("void A::b() && noexcept {}", AlignLeft);
+ verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
+ verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
+ AlignLeft);
+ verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
+ AlignLeft);
+ verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
+ verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
+ verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T) & -> void;", AlignLeft);
+ verifyFormat("void Fn(T const&) const&;", AlignLeft);
+ verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
+ verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
+ AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) & noexcept;",
+ AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) & = default;",
+ AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) && = delete;",
+ AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
+ verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
+ verifyFormat("for (foo<void() &&>& cb : X)", AlignLeft);
+
+ FormatStyle AlignMiddle = getLLVMStyle();
+ AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("void A::b() && {}", AlignMiddle);
+ verifyFormat("void A::b() && noexcept {}", AlignMiddle);
+ verifyFormat("Deleted & operator=(const Deleted &) & = default;",
+ AlignMiddle);
+ verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
+ AlignMiddle);
+ verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
+ AlignMiddle);
+ verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
+ verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
+ verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
+ verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
+ verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
+ verifyFormat("auto Function(T) & -> void;", AlignMiddle);
+ verifyFormat("void Fn(T const &) const &;", AlignMiddle);
+ verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
+ verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
+ AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) & noexcept;",
+ AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) & = default;",
+ AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) && = delete;",
+ AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
+ verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.InCStyleCasts = true;
+ verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
+ verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
+ verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
+ verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
+
+ Spaces.SpacesInParensOptions.InCStyleCasts = false;
+ Spaces.SpacesInParensOptions.Other = true;
+ verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
+ verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
+ Spaces);
+ verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
+ verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
+
+ FormatStyle BreakTemplate = getLLVMStyle();
+ BreakTemplate.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int &foo(const std::string &str) & noexcept {}\n"
+ "};",
+ BreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int &foo(const std::string &str) && noexcept {}\n"
+ "};",
+ BreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int &foo(const std::string &str) const & noexcept {}\n"
+ "};",
+ BreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int &foo(const std::string &str) const & noexcept {}\n"
+ "};",
+ BreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " auto foo(const std::string &str) && noexcept -> int & {}\n"
+ "};",
+ BreakTemplate);
+
+ FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
+ AlignLeftBreakTemplate.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+ AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int& foo(const std::string& str) & noexcept {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int& foo(const std::string& str) && noexcept {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int& foo(const std::string& str) const& noexcept {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " int& foo(const std::string& str) const&& noexcept {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " auto foo(const std::string& str) && noexcept -> int& {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ // The `&` in `Type&` should not be confused with a trailing `&` of
+ // DEPRECATED(reason) member function.
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " DEPRECATED(reason)\n"
+ " Type &foo(arguments) {}\n"
+ "};",
+ BreakTemplate);
+
+ verifyFormat("struct f {\n"
+ " template <class T>\n"
+ " DEPRECATED(reason)\n"
+ " Type& foo(arguments) {}\n"
+ "};",
+ AlignLeftBreakTemplate);
+
+ verifyFormat("void (*foopt)(int) = &func;");
+
+ FormatStyle DerivePointerAlignment = getLLVMStyle();
+ DerivePointerAlignment.DerivePointerAlignment = true;
+ // There's always a space between the function and its trailing qualifiers.
+ // This isn't evidence for PAS_Right (or for PAS_Left).
+ std::string Prefix = "void a() &;\n"
+ "void b() &;\n";
+ verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
+ verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
+ // Same if the function is an overloaded operator, and with &&.
+ Prefix = "void operator()() &&;\n"
+ "void operator()() &&;\n";
+ verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
+ verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
+ // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
+ Prefix = "void a() const &;\n"
+ "void b() const &;\n";
+ verifyFormat(Prefix + "int *x;", Prefix + "int* x;", DerivePointerAlignment);
+
+ constexpr StringRef Code("MACRO(int*, std::function<void() &&>);");
+ verifyFormat(Code, DerivePointerAlignment);
+
+ auto Style = getGoogleStyle();
+ Style.DerivePointerAlignment = true;
+ verifyFormat(Code, Style);
+}
+
+TEST_F(FormatTest, PointerAlignmentFallback) {
+ FormatStyle Style = getLLVMStyle();
+ Style.DerivePointerAlignment = true;
+
+ constexpr StringRef Code("int* p;\n"
+ "int *q;\n"
+ "int * r;");
+
+ EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
+ verifyFormat("int *p;\n"
+ "int *q;\n"
+ "int *r;",
+ Code, Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("int* p;\n"
+ "int* q;\n"
+ "int* r;",
+ Code, Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("int * p;\n"
+ "int * q;\n"
+ "int * r;",
+ Code, Style);
+}
+
+TEST_F(FormatTest, UnderstandsNewAndDelete) {
+ verifyFormat("A(void *p) : a(new (p) int) {}");
+ verifyFormat("void f() {\n"
+ " A *a = new A;\n"
+ " A *a = new (placement) A;\n"
+ " delete a;\n"
+ " delete (A *)a;\n"
+ "}");
+ verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
+ " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
+ " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("delete[] h->p;");
+ verifyFormat("delete[] (void *)p;");
+
+ verifyFormat("void operator delete(void *foo) ATTRIB;");
+ verifyFormat("void operator new(void *foo) ATTRIB;");
+ verifyFormat("void operator delete[](void *foo) ATTRIB;");
+ verifyFormat("void operator delete(void *ptr) noexcept;");
+
+ verifyFormat("void new(link p);\n"
+ "void delete(link p);",
+ "void new (link p);\n"
+ "void delete (link p);",
+ getLLVMStyle(FormatStyle::LK_C));
+
+ verifyFormat("{\n"
+ " p->new();\n"
+ "}\n"
+ "{\n"
+ " p->delete();\n"
+ "}",
+ "{\n"
+ " p->new ();\n"
+ "}\n"
+ "{\n"
+ " p->delete ();\n"
+ "}");
+
+ FormatStyle AfterPlacementOperator = getLLVMStyle();
+ AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ EXPECT_TRUE(
+ AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator);
+ verifyFormat("new (buf) int;", AfterPlacementOperator);
+ verifyFormat("struct A {\n"
+ " int *a;\n"
+ " A(int *p) : a(new (p) int) {\n"
+ " new (p) int;\n"
+ " int *b = new (p) int;\n"
+ " int *c = new (p) int(3);\n"
+ " delete (b);\n"
+ " }\n"
+ "};",
+ AfterPlacementOperator);
+ verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+ verifyFormat("delete (int *)p;", AfterPlacementOperator);
+
+ AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+ false;
+ verifyFormat("new(buf) int;", AfterPlacementOperator);
+ verifyFormat("struct A {\n"
+ " int *a;\n"
+ " A(int *p) : a(new(p) int) {\n"
+ " new(p) int;\n"
+ " int *b = new(p) int;\n"
+ " int *c = new(p) int(3);\n"
+ " delete(b);\n"
+ " }\n"
+ "};",
+ AfterPlacementOperator);
+ verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+ verifyFormat("delete (int *)p;", AfterPlacementOperator);
+}
+
+TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
+ verifyFormat("int *f(int *a) {}");
+ verifyFormat("int main(int argc, char **argv) {}");
+ verifyFormat("Test::Test(int b) : a(b * b) {}");
+ verifyIndependentOfContext("f(a, *a);");
+ verifyFormat("void g() { f(*a); }");
+ verifyIndependentOfContext("int a = b * 10;");
+ verifyIndependentOfContext("int a = 10 * b;");
+ verifyIndependentOfContext("int a = b * c;");
+ verifyIndependentOfContext("int a += b * c;");
+ verifyIndependentOfContext("int a -= b * c;");
+ verifyIndependentOfContext("int a *= b * c;");
+ verifyIndependentOfContext("int a /= b * c;");
+ verifyIndependentOfContext("int a = *b;");
+ verifyIndependentOfContext("int a = *b * c;");
+ verifyIndependentOfContext("int a = b * *c;");
+ verifyIndependentOfContext("int a = b * (10);");
+ verifyIndependentOfContext("S << b * (10);");
+ verifyIndependentOfContext("return 10 * b;");
+ verifyIndependentOfContext("return *b * *c;");
+ verifyIndependentOfContext("return a & ~b;");
+ verifyIndependentOfContext("f(b ? *c : *d);");
+ verifyIndependentOfContext("int a = b ? *c : *d;");
+ verifyIndependentOfContext("*b = a;");
+ verifyIndependentOfContext("a * ~b;");
+ verifyIndependentOfContext("a * !b;");
+ verifyIndependentOfContext("a * +b;");
+ verifyIndependentOfContext("a * -b;");
+ verifyIndependentOfContext("a * ++b;");
+ verifyIndependentOfContext("a * --b;");
+ verifyIndependentOfContext("a[4] * b;");
+ verifyIndependentOfContext("a[a * a] = 1;");
+ verifyIndependentOfContext("f() * b;");
+ verifyIndependentOfContext("a * [self dostuff];");
+ verifyIndependentOfContext("int x = a * (a + b);");
+ verifyIndependentOfContext("(a *)(a + b);");
+ verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
+ verifyIndependentOfContext("int *pa = (int *)&a;");
+ verifyIndependentOfContext("return sizeof(int **);");
+ verifyIndependentOfContext("return sizeof(int ******);");
+ verifyIndependentOfContext("return (int **&)a;");
+ verifyIndependentOfContext("f((*PointerToArray)[10]);");
+ verifyFormat("void f(Type (*parameter)[10]) {}");
+ verifyFormat("void f(Type (¶meter)[10]) {}");
+ verifyGoogleFormat("return sizeof(int**);");
+ verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
+ verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
+ verifyFormat("auto a = [](int **&, int ***) {};");
+ verifyFormat("auto PointerBinding = [](const char *S) {};");
+ verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
+ verifyFormat("[](const decltype(*a) &value) {}");
+ verifyFormat("[](const typeof(*a) &value) {}");
+ verifyFormat("[](const _Atomic(a *) &value) {}");
+ verifyFormat("[](const __underlying_type(a) &value) {}");
+ verifyFormat("decltype(a * b) F();");
+ verifyFormat("typeof(a * b) F();");
+ verifyFormat("#define MACRO() [](A *a) { return 1; }");
+ verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
+ verifyIndependentOfContext("typedef void (*f)(int *a);");
+ verifyIndependentOfContext("typedef void (*f)(Type *a);");
+ verifyIndependentOfContext("int i{a * b};");
+ verifyIndependentOfContext("aaa && aaa->f();");
+ verifyIndependentOfContext("int x = ~*p;");
+ verifyFormat("Constructor() : a(a), area(width * height) {}");
+ verifyFormat("Constructor() : a(a), area(a, width * height) {}");
+ verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
+ verifyFormat("void f() { f(a, c * d); }");
+ verifyFormat("void f() { f(new a(), c * d); }");
+ verifyFormat("void f(const MyOverride &override);");
+ verifyFormat("void f(const MyFinal &final);");
+ verifyIndependentOfContext("bool a = f() && override.f();");
+ verifyIndependentOfContext("bool a = f() && final.f();");
+
+ verifyIndependentOfContext("InvalidRegions[*R] = 0;");
+
+ verifyIndependentOfContext("A<int *> a;");
+ verifyIndependentOfContext("A<int **> a;");
+ verifyIndependentOfContext("A<int *, int *> a;");
+ verifyIndependentOfContext("A<int *[]> a;");
+ verifyIndependentOfContext(
+ "const char *const p = reinterpret_cast<const char *const>(q);");
+ verifyIndependentOfContext("A<int **, int **> a;");
+ verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
+ verifyFormat("for (char **a = b; *a; ++a) {\n}");
+ verifyFormat("for (; a && b;) {\n}");
+ verifyFormat("bool foo = true && [] { return false; }();");
+
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyGoogleFormat("int const* a = &b;");
+ verifyGoogleFormat("**outparam = 1;");
+ verifyGoogleFormat("*outparam = a * b;");
+ verifyGoogleFormat("int main(int argc, char** argv) {}");
+ verifyGoogleFormat("A<int*> a;");
+ verifyGoogleFormat("A<int**> a;");
+ verifyGoogleFormat("A<int*, int*> a;");
+ verifyGoogleFormat("A<int**, int**> a;");
+ verifyGoogleFormat("f(b ? *c : *d);");
+ verifyGoogleFormat("int a = b ? *c : *d;");
+ verifyGoogleFormat("Type* t = **x;");
+ verifyGoogleFormat("Type* t = *++*x;");
+ verifyGoogleFormat("*++*x;");
+ verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
+ verifyGoogleFormat("Type* t = x++ * y;");
+ verifyGoogleFormat(
+ "const char* const p = reinterpret_cast<const char* const>(q);");
+ verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
+ verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
+ verifyGoogleFormat("template <typename T>\n"
+ "void f(int i = 0, SomeType** temps = NULL);");
+
+ FormatStyle Left = getLLVMStyle();
+ Left.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("x = *a(x) = *a(y);", Left);
+ verifyFormat("for (;; *a = b) {\n}", Left);
+ verifyFormat("return *this += 1;", Left);
+ verifyFormat("throw *x;", Left);
+ verifyFormat("delete *x;", Left);
+ verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
+ verifyFormat("[](const decltype(*a)* ptr) {}", Left);
+ verifyFormat("[](const typeof(*a)* ptr) {}", Left);
+ verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
+ verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
+ verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
+ verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
+ verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
+ verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
+
+ verifyIndependentOfContext("a = *(x + y);");
+ verifyIndependentOfContext("a = &(x + y);");
+ verifyIndependentOfContext("*(x + y).call();");
+ verifyIndependentOfContext("&(x + y)->call();");
+ verifyFormat("void f() { &(*I).first; }");
+
+ verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
+ verifyFormat("f(* /* confusing comment */ foo);");
+ verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
+ verifyFormat("void foo(int * // this is the first paramters\n"
+ " ,\n"
+ " int second);");
+ verifyFormat("double term = a * // first\n"
+ " b;");
+ verifyFormat(
+ "int *MyValues = {\n"
+ " *A, // Operator detection might be confused by the '{'\n"
+ " *BB // Operator detection might be confused by previous comment\n"
+ "};");
+
+ verifyIndependentOfContext("if (int *a = &b)");
+ verifyIndependentOfContext("if (int &a = *b)");
+ verifyIndependentOfContext("if (a & b[i])");
+ verifyIndependentOfContext("if constexpr (a & b[i])");
+ verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
+ verifyIndependentOfContext("if (a * (b * c))");
+ verifyIndependentOfContext("if constexpr (a * (b * c))");
+ verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
+ verifyIndependentOfContext("if (a::b::c::d & b[i])");
+ verifyIndependentOfContext("if (*b[i])");
+ verifyIndependentOfContext("if (int *a = (&b))");
+ verifyIndependentOfContext("while (int *a = &b)");
+ verifyIndependentOfContext("while (a * (b * c))");
+ verifyIndependentOfContext("size = sizeof *a;");
+ verifyIndependentOfContext("if (a && (b = c))");
+ verifyFormat("void f() {\n"
+ " for (const int &v : Values) {\n"
+ " }\n"
+ "}");
+ verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
+ verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
+ verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
+
+ verifyFormat("#define A (!a * b)");
+ verifyFormat("#define MACRO \\\n"
+ " int *i = a * b; \\\n"
+ " void f(a *b);",
+ getLLVMStyleWithColumns(19));
+
+ verifyIndependentOfContext("A = new SomeType *[Length];");
+ verifyIndependentOfContext("A = new SomeType *[Length]();");
+ verifyIndependentOfContext("T **t = new T *;");
+ verifyIndependentOfContext("T **t = new T *();");
+ verifyGoogleFormat("A = new SomeType*[Length]();");
+ verifyGoogleFormat("A = new SomeType*[Length];");
+ verifyGoogleFormat("T** t = new T*;");
+ verifyGoogleFormat("T** t = new T*();");
+
+ verifyFormat("STATIC_ASSERT((a & b) == 0);");
+ verifyFormat("STATIC_ASSERT(0 == (a & b));");
+ verifyFormat("template <bool a, bool b> "
+ "typename t::if<x && y>::type f() {}");
+ verifyFormat("template <int *y> f() {}");
+ verifyFormat("vector<int *> v;");
+ verifyFormat("vector<int *const> v;");
+ verifyFormat("vector<int *const **const *> v;");
+ verifyFormat("vector<int *volatile> v;");
+ verifyFormat("vector<a *_Nonnull> v;");
+ verifyFormat("vector<a *_Nullable> v;");
+ verifyFormat("vector<a *_Null_unspecified> v;");
+ verifyGoogleFormat("vector<a* absl_nonnull> v;");
+ verifyGoogleFormat("vector<a* absl_nullable> v;");
+ verifyGoogleFormat("vector<a* absl_nullability_unknown> v;");
+ verifyFormat("vector<a *__ptr32> v;");
+ verifyFormat("vector<a *__ptr64> v;");
+ verifyFormat("vector<a *__capability> v;");
+ FormatStyle TypeMacros = getLLVMStyle();
+ TypeMacros.TypenameMacros = {"LIST"};
+ verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
+ verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
+ verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
+ verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
+ verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
+
+ FormatStyle CustomQualifier = getLLVMStyle();
+ // Add identifiers that should not be parsed as a qualifier by default.
+ CustomQualifier.AttributeMacros.push_back("__my_qualifier");
+ CustomQualifier.AttributeMacros.push_back("_My_qualifier");
+ CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
+ verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
+ verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
+ verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
+ verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
+ verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
+ verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
+ verifyFormat("vector<a * _NotAQualifier> v;");
+ verifyFormat("vector<a * __not_a_qualifier> v;");
+ verifyFormat("vector<a * b> v;");
+ verifyFormat("foo<b && false>();");
+ verifyFormat("foo<b & 1>();");
+ verifyFormat("foo<b & (1)>();");
+ verifyFormat("foo<b & (~0)>();");
+ verifyFormat("foo<b & (true)>();");
+ verifyFormat("foo<b & ((1))>();");
+ verifyFormat("foo<b & (/*comment*/ 1)>();");
+ verifyFormat("decltype(*::std::declval<const T &>()) void F();");
+ verifyFormat("typeof(*::std::declval<const T &>()) void F();");
+ verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
+ verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
+ verifyFormat(
+ "template <class T, class = typename std::enable_if<\n"
+ " std::is_integral<T>::value &&\n"
+ " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
+ "void F();",
+ getLLVMStyleWithColumns(70));
+ verifyFormat("template <class T,\n"
+ " class = typename std::enable_if<\n"
+ " std::is_integral<T>::value &&\n"
+ " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
+ " class U>\n"
+ "void F();",
+ getLLVMStyleWithColumns(70));
+ verifyFormat(
+ "template <class T,\n"
+ " class = typename ::std::enable_if<\n"
+ " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
+ "void F();",
+ getGoogleStyleWithColumns(68));
+
+ FormatStyle Style = getLLVMStyle();
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("struct {\n"
+ "}* ptr;",
+ Style);
+ verifyFormat("union {\n"
+ "}* ptr;",
+ Style);
+ verifyFormat("class {\n"
+ "}* ptr;",
+ Style);
+ // Don't confuse a multiplication after a brace-initialized expression with
+ // a class pointer.
+ verifyFormat("int i = int{42} * 34;", Style);
+ verifyFormat("struct {\n"
+ "}&& ptr = {};",
+ Style);
+ verifyFormat("union {\n"
+ "}&& ptr = {};",
+ Style);
+ verifyFormat("class {\n"
+ "}&& ptr = {};",
+ Style);
+ verifyFormat("bool b = 3 == int{3} && true;");
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("struct {\n"
+ "} * ptr;",
+ Style);
+ verifyFormat("union {\n"
+ "} * ptr;",
+ Style);
+ verifyFormat("class {\n"
+ "} * ptr;",
+ Style);
+ verifyFormat("struct {\n"
+ "} && ptr = {};",
+ Style);
+ verifyFormat("union {\n"
+ "} && ptr = {};",
+ Style);
+ verifyFormat("class {\n"
+ "} && ptr = {};",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Right;
+ verifyFormat("struct {\n"
+ "} *ptr;",
+ Style);
+ verifyFormat("union {\n"
+ "} *ptr;",
+ Style);
+ verifyFormat("class {\n"
+ "} *ptr;",
+ Style);
+ verifyFormat("struct {\n"
+ "} &&ptr = {};",
+ Style);
+ verifyFormat("union {\n"
+ "} &&ptr = {};",
+ Style);
+ verifyFormat("class {\n"
+ "} &&ptr = {};",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("delete[] *ptr;", Style);
+ verifyFormat("delete[] **ptr;", Style);
+ verifyFormat("delete[] *(ptr);", Style);
+
+ verifyIndependentOfContext("MACRO(int *i);");
+ verifyIndependentOfContext("MACRO(auto *a);");
+ verifyIndependentOfContext("MACRO(const A *a);");
+ verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
+ verifyIndependentOfContext("MACRO(decltype(A) *a);");
+ verifyIndependentOfContext("MACRO(typeof(A) *a);");
+ verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
+ verifyIndependentOfContext("MACRO(A *const a);");
+ verifyIndependentOfContext("MACRO(A *restrict a);");
+ verifyIndependentOfContext("MACRO(A *__restrict__ a);");
+ verifyIndependentOfContext("MACRO(A *__restrict a);");
+ verifyIndependentOfContext("MACRO(A *volatile a);");
+ verifyIndependentOfContext("MACRO(A *__volatile a);");
+ verifyIndependentOfContext("MACRO(A *__volatile__ a);");
+ verifyIndependentOfContext("MACRO(A *_Nonnull a);");
+ verifyIndependentOfContext("MACRO(A *_Nullable a);");
+ verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
+
+ Style = getGoogleStyle();
+ verifyIndependentOfContext("MACRO(A* absl_nonnull a);", Style);
+ verifyIndependentOfContext("MACRO(A* absl_nullable a);", Style);
+ verifyIndependentOfContext("MACRO(A* absl_nullability_unknown a);", Style);
+
+ verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
+ verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
+ verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
+ verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
+ verifyIndependentOfContext("MACRO(A *__ptr32 a);");
+ verifyIndependentOfContext("MACRO(A *__ptr64 a);");
+ verifyIndependentOfContext("MACRO(A *__capability);");
+ verifyIndependentOfContext("MACRO(A &__capability);");
+ verifyFormat("MACRO(A *__my_qualifier);"); // type declaration
+ verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
+ // If we add __my_qualifier to AttributeMacros it should always be parsed as
+ // a type declaration:
+ verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
+ verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+ // Also check that TypenameMacros prevents parsing it as multiplication:
+ verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
+ verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
+
+ verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
+ verifyFormat("void f() { f(float{1}, a * a); }");
+ verifyFormat("void f() { f(float(1), a * a); }");
+
+ verifyFormat("f((void (*)(int))g);");
+ verifyFormat("f((void (&)(int))g);");
+ verifyFormat("f((void (^)(int))g);");
+
+ // FIXME: Is there a way to make this work?
+ // verifyIndependentOfContext("MACRO(A *a);");
+ verifyFormat("MACRO(A &B);");
+ verifyFormat("MACRO(A *B);");
+ verifyFormat("void f() { MACRO(A * B); }");
+ verifyFormat("void f() { MACRO(A & B); }");
+
+ // This lambda was mis-formatted after D88956 (treating it as a binop):
+ verifyFormat("auto x = [](const decltype(x) &ptr) {};");
+ verifyFormat("auto x = [](const decltype(x) *ptr) {};");
+ verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
+ verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
+
+ verifyFormat("DatumHandle const *operator->() const { return input_; }");
+ verifyFormat("return options != nullptr && operator==(*options);");
+
+ verifyFormat("#define OP(x) \\\n"
+ " ostream &operator<<(ostream &s, const A &a) { \\\n"
+ " return s << a.DebugString(); \\\n"
+ " }",
+ "#define OP(x) \\\n"
+ " ostream &operator<<(ostream &s, const A &a) { \\\n"
+ " return s << a.DebugString(); \\\n"
+ " }",
+ getLLVMStyleWithColumns(50));
+
+ verifyFormat("#define FOO \\\n"
+ " void foo() { \\\n"
+ " operator+(a * b); \\\n"
+ " }",
+ getLLVMStyleWithColumns(25));
+
+ // FIXME: We cannot handle this case yet; we might be able to figure out that
+ // foo<x> d > v; doesn't make sense.
+ verifyFormat("foo<a<b && c> d> v;");
+
+ FormatStyle PointerMiddle = getLLVMStyle();
+ PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("delete *x;", PointerMiddle);
+ verifyFormat("int * x;", PointerMiddle);
+ verifyFormat("int *[] x;", PointerMiddle);
+ verifyFormat("template <int * y> f() {}", PointerMiddle);
+ verifyFormat("int * f(int * a) {}", PointerMiddle);
+ verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
+ verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
+ verifyFormat("A<int *> a;", PointerMiddle);
+ verifyFormat("A<int **> a;", PointerMiddle);
+ verifyFormat("A<int *, int *> a;", PointerMiddle);
+ verifyFormat("A<int *[]> a;", PointerMiddle);
+ verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
+ verifyFormat("A = new SomeType *[Length];", PointerMiddle);
+ verifyFormat("T ** t = new T *;", PointerMiddle);
+
+ // Member function reference qualifiers aren't binary operators.
+ verifyFormat("string // break\n"
+ "operator()() & {}");
+ verifyFormat("string // break\n"
+ "operator()() && {}");
+ verifyGoogleFormat("template <typename T>\n"
+ "auto x() & -> int {}");
+
+ // Should be binary operators when used as an argument expression (overloaded
+ // operator invoked as a member function).
+ verifyFormat("void f() { a.operator()(a * a); }");
+ verifyFormat("void f() { a->operator()(a & a); }");
+ verifyFormat("void f() { a.operator()(*a & *a); }");
+ verifyFormat("void f() { a->operator()(*a * *a); }");
+
+ verifyFormat("int operator()(T (&&)[N]) { return 1; }");
+ verifyFormat("int operator()(T (&)[N]) { return 0; }");
+
+ verifyFormat("val1 & val2;");
+ verifyFormat("val1 & val2 & val3;");
+ verifyFormat("class c {\n"
+ " void func(type &a) { a & member; }\n"
+ " anotherType &member;\n"
+ "}");
+}
+
+TEST_F(FormatTest, UnderstandsAttributes) {
+ verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
+ "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
+ verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
+ FormatStyle AfterType = getLLVMStyle();
+ AfterType.BreakAfterReturnType = FormatStyle::RTBS_All;
+ verifyFormat("__attribute__((nodebug)) void\n"
+ "foo() {}",
+ AfterType);
+ verifyFormat("__unused void\n"
+ "foo() {}",
+ AfterType);
+
+ FormatStyle CustomAttrs = getLLVMStyle();
+ CustomAttrs.AttributeMacros.push_back("my_attr_name");
+ verifyFormat("void MyGoodOldFunction(\n"
+ " void *const long_enough = nullptr,\n"
+ " void *my_attr_name even_longeeeeeeeeeeeeeeeeer = nullptr);",
+ CustomAttrs);
+
+ CustomAttrs.AttributeMacros.push_back("__unused");
+ CustomAttrs.AttributeMacros.push_back("__attr1");
+ CustomAttrs.AttributeMacros.push_back("__attr2");
+ CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
+ verifyFormat("vector<SomeType *__attribute((foo))> v;");
+ verifyFormat("vector<SomeType *__attribute__((foo))> v;");
+ verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
+ // Check that it is parsed as a multiplication without AttributeMacros and
+ // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
+ verifyFormat("vector<SomeType * __attr1> v;");
+ verifyFormat("vector<SomeType __attr1 *> v;");
+ verifyFormat("vector<SomeType __attr1 *const> v;");
+ verifyFormat("vector<SomeType __attr1 * __attr2> v;");
+ verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
+ verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
+ verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
+ verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
+ verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
+ verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
+ verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
+ verifyFormat("__attr1 ::qualified_type f();", CustomAttrs);
+ verifyFormat("__attr1() ::qualified_type f();", CustomAttrs);
+ verifyFormat("__attr1(nodebug) ::qualified_type f();", CustomAttrs);
+
+ // Check that these are not parsed as function declarations:
+ CustomAttrs.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle();
+ CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("SomeType s(InitValue);", CustomAttrs);
+ verifyFormat("SomeType s{InitValue};", CustomAttrs);
+ verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
+ verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
+ verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
+ verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
+ verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
+ verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
+ verifyGoogleFormat("SomeType* absl_nonnull s(InitValue);");
+ verifyGoogleFormat("SomeType* absl_nonnull s{InitValue};");
+ verifyGoogleFormat("SomeType* absl_nullable s(InitValue);");
+ verifyGoogleFormat("SomeType* absl_nullable s{InitValue};");
+ verifyGoogleFormat("SomeType* absl_nullability_unknown s(InitValue);");
+ verifyGoogleFormat("SomeType* absl_nullability_unknown s{InitValue};");
+
+ auto Style = getLLVMStyleWithColumns(60);
+ Style.AttributeMacros.push_back("my_fancy_attr");
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("void foo(const MyLongTypeNameeeeeeeeeeeee* my_fancy_attr\n"
+ " testttttttttt);",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
+ // Check that qualifiers on pointers don't break parsing of casts.
+ verifyFormat("x = (foo *const)*v;");
+ verifyFormat("x = (foo *volatile)*v;");
+ verifyFormat("x = (foo *restrict)*v;");
+ verifyFormat("x = (foo *__attribute__((foo)))*v;");
+ verifyFormat("x = (foo *_Nonnull)*v;");
+ verifyFormat("x = (foo *_Nullable)*v;");
+ verifyFormat("x = (foo *_Null_unspecified)*v;");
+ verifyGoogleFormat("x = (foo* absl_nonnull)*v;");
+ verifyGoogleFormat("x = (foo* absl_nullable)*v;");
+ verifyGoogleFormat("x = (foo* absl_nullability_unknown)*v;");
+ verifyFormat("x = (foo *[[clang::attr]])*v;");
+ verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
+ verifyFormat("x = (foo *__ptr32)*v;");
+ verifyFormat("x = (foo *__ptr64)*v;");
+ verifyFormat("x = (foo *__capability)*v;");
+
+ // Check that we handle multiple trailing qualifiers and skip them all to
+ // determine that the expression is a cast to a pointer type.
+ FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
+ FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
+ LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
+ StringRef AllQualifiers =
+ "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
+ "_Nullable [[clang::attr]] __ptr32 __ptr64 __capability";
+ verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
+ verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
+
+ // Also check that address-of is not parsed as a binary bitwise-and:
+ verifyFormat("x = (foo *const)&v;");
+ verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
+ verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
+
+ // Check custom qualifiers:
+ FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
+ CustomQualifier.AttributeMacros.push_back("__my_qualifier");
+ verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
+ verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
+ verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
+ CustomQualifier);
+ verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
+ CustomQualifier);
+
+ // Check that unknown identifiers result in binary operator parsing:
+ verifyFormat("x = (foo * __unknown_qualifier) * v;");
+ verifyFormat("x = (foo * __unknown_qualifier) & v;");
+}
+
+TEST_F(FormatTest, UnderstandsSquareAttributes) {
+ verifyFormat("SomeType s [[unused]] (InitValue);");
+ verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
+ verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
+ verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
+ verifyFormat("[[suppress(type.5)]] int uninitialized_on_purpose;");
+ verifyFormat("void f() [[deprecated(\"so sorry\")]];");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
+ verifyFormat("[[nodiscard]] bool f() { return false; }");
+ verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}");
+ verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}");
+ verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}");
+ verifyFormat("[[nodiscard]] ::qualified_type f();");
+
+ // Make sure we do not mistake attributes for array subscripts.
+ verifyFormat("int a() {}\n"
+ "[[unused]] int b() {}");
+ verifyFormat("NSArray *arr;\n"
+ "arr[[Foo() bar]];");
+
+ // On the other hand, we still need to correctly find array subscripts.
+ verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
+
+ // Make sure that we do not mistake Objective-C method inside array literals
+ // as attributes, even if those method names are also keywords.
+ verifyFormat("@[ [foo bar] ];");
+ verifyFormat("@[ [NSArray class] ];");
+ verifyFormat("@[ [foo enum] ];");
+
+ verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
+
+ // Make sure we do not parse attributes as lambda introducers.
+ FormatStyle MultiLineFunctions = getLLVMStyle();
+ MultiLineFunctions.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle();
+ verifyFormat("[[unused]] int b() {\n"
+ " return 42;\n"
+ "}",
+ MultiLineFunctions);
+}
+
+TEST_F(FormatTest, AttributeClass) {
+ FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
+ verifyFormat("class S {\n"
+ " S(S&&) = default;\n"
+ "};",
+ Style);
+ verifyFormat("class [[nodiscard]] S {\n"
+ " S(S&&) = default;\n"
+ "};",
+ Style);
+ verifyFormat("class __attribute((maybeunused)) S {\n"
+ " S(S&&) = default;\n"
+ "};",
+ Style);
+ verifyFormat("struct S {\n"
+ " S(S&&) = default;\n"
+ "};",
+ Style);
+ verifyFormat("struct [[nodiscard]] S {\n"
+ " S(S&&) = default;\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, AttributesAfterMacro) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("MACRO;\n"
+ "__attribute__((maybe_unused)) int foo() {\n"
+ " //...\n"
+ "}");
+
+ verifyFormat("MACRO;\n"
+ "[[nodiscard]] int foo() {\n"
+ " //...\n"
+ "}");
+
+ verifyNoChange("MACRO\n\n"
+ "__attribute__((maybe_unused)) int foo() {\n"
+ " //...\n"
+ "}");
+
+ verifyNoChange("MACRO\n\n"
+ "[[nodiscard]] int foo() {\n"
+ " //...\n"
+ "}");
+}
+
+TEST_F(FormatTest, AttributePenaltyBreaking) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
+ " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
+ Style);
+ verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
+ " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
+ Style);
+ verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
+ "shared_ptr<ALongTypeName> &C d) {\n}",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandsEllipsis) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("int printf(const char *fmt, ...);");
+ verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
+ verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
+
+ verifyFormat("template <int *...PP> a;", Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
+
+ verifyFormat("template <int*... PP> a;", Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("template <int *... PP> a;", Style);
+}
+
+TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
+ auto Style = getGoogleStyle();
+ EXPECT_FALSE(Style.DerivePointerAlignment);
+ Style.DerivePointerAlignment = true;
+
+ verifyFormat("int *a;\n"
+ "int *a;\n"
+ "int *a;",
+ "int *a;\n"
+ "int* a;\n"
+ "int *a;",
+ Style);
+ verifyFormat("int* a;\n"
+ "int* a;\n"
+ "int* a;",
+ "int* a;\n"
+ "int* a;\n"
+ "int *a;",
+ Style);
+ verifyFormat("int *a;\n"
+ "int *a;\n"
+ "int *a;",
+ "int *a;\n"
+ "int * a;\n"
+ "int * a;",
+ Style);
+ verifyFormat("auto x = [] {\n"
+ " int *a;\n"
+ " int *a;\n"
+ " int *a;\n"
+ "};",
+ "auto x=[]{int *a;\n"
+ "int * a;\n"
+ "int * a;};",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandsRvalueReferences) {
+ verifyFormat("int f(int &&a) {}");
+ verifyFormat("int f(int a, char &&b) {}");
+ verifyFormat("void f() { int &&a = b; }");
+ verifyGoogleFormat("int f(int a, char&& b) {}");
+ verifyGoogleFormat("void f() { int&& a = b; }");
+
+ verifyIndependentOfContext("A<int &&> a;");
+ verifyIndependentOfContext("A<int &&, int &&> a;");
+ verifyGoogleFormat("A<int&&> a;");
+ verifyGoogleFormat("A<int&&, int&&> a;");
+
+ // Not rvalue references:
+ verifyFormat("template <bool B, bool C> class A {\n"
+ " static_assert(B && C, \"Something is wrong\");\n"
+ "};");
+ verifyFormat("template <typename T> void swap() noexcept(Bar<T> && Foo<T>);");
+ verifyFormat("template <typename T> struct S {\n"
+ " explicit(Bar<T> && Foo<T>) S(const S &);\n"
+ "};");
+ verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
+ verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
+ verifyFormat("#define A(a, b) (a && b)");
+}
+
+TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
+ verifyFormat("void f() {\n"
+ " x[aaaaaaaaa -\n"
+ " b] = 23;\n"
+ "}",
+ getLLVMStyleWithColumns(15));
+}
+
+TEST_F(FormatTest, FormatsCasts) {
+ verifyFormat("Type *A = static_cast<Type *>(P);");
+ verifyFormat("static_cast<Type *>(P);");
+ verifyFormat("static_cast<Type &>(Fun)(Args);");
+ verifyFormat("static_cast<Type &>(*Fun)(Args);");
+ verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;");
+ // Check that static_cast<...>(...) does not require the next token to be on
+ // the same line.
+ verifyFormat("some_loooong_output << something_something__ << "
+ "static_cast<const void *>(R)\n"
+ " << something;");
+ verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
+ verifyFormat("const_cast<Type &>(*Fun)(Args);");
+ verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
+ verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
+ verifyFormat("Type *A = (Type *)P;");
+ verifyFormat("Type *A = (vector<Type *, int *>)P;");
+ verifyFormat("int a = (int)(2.0f);");
+ verifyFormat("int a = (int)2.0f;");
+ verifyFormat("x[(int32)y];");
+ verifyFormat("x = (int32)y;");
+ verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
+ verifyFormat("int a = (int)*b;");
+ verifyFormat("int a = (int)2.0f;");
+ verifyFormat("int a = (int)~0;");
+ verifyFormat("int a = (int)++a;");
+ verifyFormat("int a = (int)sizeof(int);");
+ verifyFormat("int a = (int)+2;");
+ verifyFormat("my_int a = (my_int)2.0f;");
+ verifyFormat("my_int a = (my_int)sizeof(int);");
+ verifyFormat("return (my_int)aaa;");
+ verifyFormat("throw (my_int)aaa;");
+ verifyFormat("#define x ((int)-1)");
+ verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
+ verifyFormat("#define p(q) ((int *)&q)");
+ verifyFormat("fn(a)(b) + 1;");
+
+ verifyFormat("void f() { my_int a = (my_int)*b; }");
+ verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
+ verifyFormat("my_int a = (my_int)~0;");
+ verifyFormat("my_int a = (my_int)++a;");
+ verifyFormat("my_int a = (my_int)-2;");
+ verifyFormat("my_int a = (my_int)1;");
+ verifyFormat("my_int a = (my_int *)1;");
+ verifyFormat("my_int a = (const my_int)-1;");
+ verifyFormat("my_int a = (const my_int *)-1;");
+ verifyFormat("my_int a = (my_int)(my_int)-1;");
+ verifyFormat("my_int a = (ns::my_int)-2;");
+ verifyFormat("case (my_int)ONE:");
+ verifyFormat("auto x = (X)this;");
+ // Casts in Obj-C style calls used to not be recognized as such.
+ verifyGoogleFormat("int a = [(type*)[((type*)val) arg] arg];");
+
+ // FIXME: single value wrapped with paren will be treated as cast.
+ verifyFormat("void f(int i = (kValue)*kMask) {}");
+
+ verifyFormat("{\n"
+ " (void)F;\n"
+ "}");
+
+ // Don't break after a cast's
+ verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
+ " bbbbbbbbbbbbbbbbbbbbbb);");
+
+ verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
+ verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
+ verifyFormat("#define CONF_BOOL(x) (bool)(x)");
+ verifyFormat("bool *y = (bool *)(void *)(x);");
+ verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
+ verifyFormat("bool *y = (bool *)(void *)(int)(x);");
+ verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
+ verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
+
+ // These are not casts.
+ verifyFormat("void f(int *) {}");
+ verifyFormat("f(foo)->b;");
+ verifyFormat("f(foo).b;");
+ verifyFormat("f(foo)(b);");
+ verifyFormat("f(foo)[b];");
+ verifyFormat("[](foo) { return 4; }(bar);");
+ verifyFormat("(*funptr)(foo)[4];");
+ verifyFormat("funptrs[4](foo)[4];");
+ verifyFormat("void f(int *);");
+ verifyFormat("void f(int *) = 0;");
+ verifyFormat("void f(SmallVector<int>) {}");
+ verifyFormat("void f(SmallVector<int>);");
+ verifyFormat("void f(SmallVector<int>) = 0;");
+ verifyFormat("void f(int i = (kA * kB) & kMask) {}");
+ verifyFormat("int a = sizeof(int) * b;");
+ verifyGoogleFormat("int a = alignof(int) * b;");
+ verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
+ verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
+ verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
+
+ // These are not casts, but at some point were confused with casts.
+ verifyFormat("virtual void foo(int *) override;");
+ verifyFormat("virtual void foo(char &) const;");
+ verifyFormat("virtual void foo(int *a, char *) const;");
+ verifyFormat("int a = sizeof(int *) + b;");
+ verifyGoogleFormat("int a = alignof(int*) + b;");
+ verifyFormat("bool b = f(g<int>) && c;");
+ verifyFormat("typedef void (*f)(int i) func;");
+ verifyFormat("void operator++(int) noexcept;");
+ verifyFormat("void operator++(int &) noexcept;");
+ verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
+ "&) noexcept;");
+ verifyFormat(
+ "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
+ verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
+ verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
+ verifyFormat("void operator delete(nothrow_t &) noexcept;");
+ verifyFormat("void operator delete(foo &) noexcept;");
+ verifyFormat("void operator delete(foo) noexcept;");
+ verifyFormat("void operator delete(int) noexcept;");
+ verifyFormat("void operator delete(int &) noexcept;");
+ verifyFormat("void operator delete(int &) volatile noexcept;");
+ verifyFormat("void operator delete(int &) const");
+ verifyFormat("void operator delete(int &) = default");
+ verifyFormat("void operator delete(int &) = delete");
+ verifyFormat("void operator delete(int &) [[noreturn]]");
+ verifyFormat("void operator delete(int &) throw();");
+ verifyFormat("void operator delete(int &) throw(int);");
+ verifyFormat("auto operator delete(int &) -> int;");
+ verifyFormat("auto operator delete(int &) override");
+ verifyFormat("auto operator delete(int &) final");
+
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
+ // FIXME: The indentation here is not ideal.
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
+ " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
+}
+
+TEST_F(FormatTest, FormatsFunctionTypes) {
+ verifyFormat("A<bool()> a;");
+ verifyFormat("A<SomeType()> a;");
+ verifyFormat("A<void (*)(int, std::string)> a;");
+ verifyFormat("A<void *(int)>;");
+ verifyFormat("void *(*a)(int *, SomeType *);");
+ verifyFormat("int (*func)(void *);");
+ verifyFormat("void f() { int (*func)(void *); }");
+ verifyFormat("template <class CallbackClass>\n"
+ "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
+
+ verifyGoogleFormat("A<void*(int*, SomeType*)>;");
+ verifyGoogleFormat("void* (*a)(int);");
+ verifyGoogleFormat(
+ "template <class CallbackClass>\n"
+ "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
+
+ // Other constructs can look somewhat like function types:
+ verifyFormat("A<sizeof(*x)> a;");
+ verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
+ verifyFormat("some_var = function(*some_pointer_var)[0];");
+ verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
+ verifyFormat("int x = f(&h)();");
+ verifyFormat("returnsFunction(¶m1, ¶m2)(param);");
+ verifyFormat("std::function<\n"
+ " LooooooooooongTemplatedType<\n"
+ " SomeType>*(\n"
+ " LooooooooooooooooongType type)>\n"
+ " function;",
+ getGoogleStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, FormatsPointersToArrayTypes) {
+ verifyFormat("A (*foo_)[6];");
+ verifyFormat("vector<int> (*foo_)[6];");
+}
+
+TEST_F(FormatTest, BreaksLongVariableDeclarations) {
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " LoooooooooooooooooooooooooooooooooooooooongVariable;");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
+ " LoooooooooooooooooooooooooooooooooooooooongVariable;");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " *LoooooooooooooooooooooooooooooooooooooooongVariable;");
+
+ // Different ways of ()-initializiation.
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " LoooooooooooooooooooooooooooooooooooooooongVariable({});");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
+
+ // Lambdas should not confuse the variable declaration heuristic.
+ verifyFormat("LooooooooooooooooongType\n"
+ " variable(nullptr, [](A *a) {});",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, BreaksLongDeclarations) {
+ verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
+ " AnotherNameForTheLongType;");
+ verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
+ "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
+ "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
+ FormatStyle Indented = getLLVMStyle();
+ Indented.IndentWrappedFunctionNames = true;
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ " LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
+ Indented);
+ verifyFormat(
+ "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
+ Indented);
+ verifyFormat(
+ "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
+ " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
+ Indented);
+ verifyFormat(
+ "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
+ " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
+ Indented);
+
+ // FIXME: Without the comment, this breaks after "(".
+ verifyGoogleFormat(
+ "LoooooooooooooooooooooooooooooooooooooooongType // break\n"
+ " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();");
+
+ verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
+ " int LoooooooooooooooooooongParam2) {}");
+ verifyFormat(
+ "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
+ " SourceLocation L, IdentifierIn *II,\n"
+ " Type *T) {}");
+ verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
+ "ReallyReaaallyLongFunctionName(\n"
+ " const std::string &SomeParameter,\n"
+ " const SomeType<string, SomeOtherTemplateParameter>\n"
+ " &ReallyReallyLongParameterName,\n"
+ " const SomeType<string, SomeOtherTemplateParameter>\n"
+ " &AnotherLongParameterName) {}");
+ verifyFormat("template <typename A>\n"
+ "SomeLoooooooooooooooooooooongType<\n"
+ " typename some_namespace::SomeOtherType<A>::Type>\n"
+ "Function() {}");
+
+ verifyGoogleFormat(
+ "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa;");
+ verifyGoogleFormat(
+ "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
+ " SourceLocation L) {}");
+ verifyGoogleFormat(
+ "some_namespace::LongReturnType\n"
+ "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
+ " int first_long_parameter, int second_parameter) {}");
+
+ verifyGoogleFormat("template <typename T>\n"
+ "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
+ "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
+ verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
+ " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+
+ verifyFormat("template <typename T> // Templates on own line.\n"
+ "static int // Some comment.\n"
+ "MyFunction(int a);");
+}
+
+TEST_F(FormatTest, FormatsAccessModifiers) {
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
+ FormatStyle::ELBAMS_LogicalBlock);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo { /* comment */\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ Style);
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo { /* comment */\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ "struct foo { /* comment */\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ Style);
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo { /* comment */\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ Style);
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
+ verifyNoChange("struct foo {\n"
+ "\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyNoChange("struct foo { /* comment */\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo { /* comment */\n"
+ "private:\n"
+ " int i;\n"
+ " // comment\n"
+ "private:\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyNoChange("struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ "private:\n"
+ " int i;\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#endif\n"
+ " int j;\n"
+ "};",
+ Style);
+ Style.AttributeMacros.push_back("FOO");
+ Style.AttributeMacros.push_back("BAR");
+ verifyFormat("struct foo {\n"
+ "FOO private:\n"
+ " int i;\n"
+ "BAR(x) protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ FormatStyle NoEmptyLines = getLLVMStyle();
+ NoEmptyLines.MaxEmptyLinesToKeep = 0;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "public:\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ NoEmptyLines);
+
+ NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "private:\n"
+ " int i;\n"
+ "public:\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ NoEmptyLines);
+
+ NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "public:\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ NoEmptyLines);
+}
+
+TEST_F(FormatTest, FormatsAfterAccessModifiers) {
+
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ // Check if lines are removed.
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ // Check if lines are added.
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ // Leave tests rely on the code layout, test::messUp can not be used.
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
+ Style.MaxEmptyLinesToKeep = 0u;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ // Check if MaxEmptyLinesToKeep is respected.
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n\n\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n\n\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ Style.MaxEmptyLinesToKeep = 1u;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n"
+ " int j;\n"
+ "};",
+ Style);
+ // Check if no lines are kept.
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ " int j;\n"
+ "};",
+ Style);
+ // Check if MaxEmptyLinesToKeep is respected.
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n"
+ " int j;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n\n\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n\n\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ Style.MaxEmptyLinesToKeep = 10u;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ " void f() {}\n"
+ "\n"
+ "private:\n"
+ "\n\n\n"
+ " int i;\n"
+ "\n"
+ "protected:\n"
+ "\n\n\n"
+ " int j;\n"
+ "};",
+ Style);
+
+ // Test with comments.
+ Style = getLLVMStyle();
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ " int i;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ "\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ "\n"
+ " int i;\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ " // comment\n"
+ " void f() {}\n"
+ "\n"
+ "private: /* comment */\n"
+ "\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ // Test with preprocessor defines.
+ Style = getLLVMStyle();
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ Style);
+ verifyNoChange("struct foo {\n"
+ "#ifdef FOO\n"
+ "#else\n"
+ "private:\n"
+ "\n"
+ "#endif\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "#else\n"
+ "private:\n"
+ "\n"
+ "#endif\n"
+ "};",
+ "struct foo {\n"
+ "#ifdef FOO\n"
+ "#else\n"
+ "private:\n"
+ "\n"
+ "\n"
+ "#endif\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#else\n"
+ "#endif\n"
+ "};",
+ "struct foo {\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "\n"
+ "\n"
+ "#else\n"
+ "#endif\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "#if 0\n"
+ "#else\n"
+ "#endif\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "#endif\n"
+ "};",
+ "struct foo {\n"
+ "#if 0\n"
+ "#else\n"
+ "#endif\n"
+ "#ifdef FOO\n"
+ "private:\n"
+ "\n"
+ "\n"
+ "#endif\n"
+ "};",
+ Style);
+
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ Style);
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ "#ifdef FOO\n"
+ "#endif\n"
+ " void f() {}\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
+ // Combined tests of EmptyLineAfterAccessModifier and
+ // EmptyLineBeforeAccessModifier.
+ FormatStyle Style = getLLVMStyle();
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.MaxEmptyLinesToKeep = 10u;
+ // Both remove all new lines.
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ // Leave tests rely on the code layout, test::messUp can not be used.
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
+ Style.MaxEmptyLinesToKeep = 10u;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+ Style.MaxEmptyLinesToKeep = 3u;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+ Style.MaxEmptyLinesToKeep = 1u;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style); // Based on new lines in original document and not
+ // on the setting.
+
+ Style.MaxEmptyLinesToKeep = 10u;
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
+ // Newlines are kept if they are greater than zero,
+ // test::messUp removes all new lines which changes the logic
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ // test::messUp removes all new lines which changes the logic
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style); // test::messUp removes all new lines which changes
+ // the logic.
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
+ verifyNoChange("struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style); // test::messUp removes all new lines which changes
+ // the logic.
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+
+ Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
+ Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
+ verifyFormat("struct foo {\n"
+ "private:\n"
+ "protected:\n"
+ "};",
+ "struct foo {\n"
+ "private:\n"
+ "\n\n\n"
+ "protected:\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsArrays) {
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
+ " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
+ " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
+ " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
+ " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
+ verifyFormat(
+ "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
+ " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
+ " .aaaaaaaaaaaaaaaaaaaaaa();");
+
+ verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
+ verifyFormat(
+ "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
+ " .aaaaaaa[0]\n"
+ " .aaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("a[::b::c];");
+
+ verifyFormat("{\n"
+ " (*a)[0] = 1;\n"
+ "}");
+
+ verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
+
+ FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
+ verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
+}
+
+TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
+ verifyFormat("(a)->b();");
+ verifyFormat("--a;");
+}
+
+TEST_F(FormatTest, HandlesIncludeDirectives) {
+ verifyFormat("#include <string>\n"
+ "#include <a/b/c.h>\n"
+ "#include \"a/b/string\"\n"
+ "#include \"string.h\"\n"
+ "#include \"string.h\"\n"
+ "#include <a-a>\n"
+ "#include < path with space >\n"
+ "#include_next <test.h>"
+ "#include \"abc.h\" // this is included for ABC\n"
+ "#include \"some long include\" // with a comment\n"
+ "#include \"some very long include path\"\n"
+ "#include <some/very/long/include/path>",
+ getLLVMStyleWithColumns(35));
+ verifyFormat("#include \"a.h\"", "#include \"a.h\"");
+ verifyFormat("#include <a>", "#include<a>");
+
+ verifyFormat("#import <string>");
+ verifyFormat("#import <a/b/c.h>");
+ verifyFormat("#import \"a/b/string\"");
+ verifyFormat("#import \"string.h\"");
+ verifyFormat("#import \"string.h\"");
+ verifyFormat("#if __has_include(<strstream>)\n"
+ "#include <strstream>\n"
+ "#endif");
+
+ verifyFormat("#define MY_IMPORT <a/b>");
+
+ verifyFormat("#if __has_include(<a/b>)");
+ verifyFormat("#if __has_include_next(<a/b>)");
+ verifyFormat("#define F __has_include(<a/b>)");
+ verifyFormat("#define F __has_include_next(<a/b>)");
+
+ // Protocol buffer definition or missing "#".
+ verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
+ getLLVMStyleWithColumns(30));
+
+ FormatStyle Style = getLLVMStyle();
+ Style.AlwaysBreakBeforeMultilineStrings = true;
+ Style.ColumnLimit = 0;
+ verifyFormat("#import \"abc.h\"", Style);
+
+ // But 'import' might also be a regular C++ namespace.
+ verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("import::Bar foo(val ? 2 : 1);");
+}
+
+//===----------------------------------------------------------------------===//
+// Error recovery tests.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, IncompleteParameterLists) {
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
+ " double *min_x,\n"
+ " double *max_x,\n"
+ " double *min_y,\n"
+ " double *max_y,\n"
+ " double *min_z,\n"
+ " double *max_z, ) {}",
+ NoBinPacking);
+}
+
+TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
+ verifyFormat("void f() { return; }\n42");
+ verifyFormat("void f() {\n"
+ " if (0)\n"
+ " return;\n"
+ "}\n"
+ "42");
+ verifyFormat("void f() { return }\n42");
+ verifyFormat("void f() {\n"
+ " if (0)\n"
+ " return\n"
+ "}\n"
+ "42");
+}
+
+TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
+ verifyFormat("void f() { return }", "void f ( ) { return }");
+ verifyFormat("void f() {\n"
+ " if (a)\n"
+ " return\n"
+ "}",
+ "void f ( ) { if ( a ) return }");
+ verifyFormat("namespace N {\n"
+ "void f()\n"
+ "}",
+ "namespace N { void f() }");
+ verifyFormat("namespace N {\n"
+ "void f() {}\n"
+ "void g()\n"
+ "} // namespace N",
+ "namespace N { void f( ) { } void g( ) }");
+}
+
+TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
+ verifyFormat("int aaaaaaaa =\n"
+ " // Overlylongcomment\n"
+ " b;",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("function(\n"
+ " ShortArgument,\n"
+ " LoooooooooooongArgument);",
+ getLLVMStyleWithColumns(20));
+}
+
+TEST_F(FormatTest, IncorrectAccessSpecifier) {
+ verifyFormat("public:");
+ verifyFormat("class A {\n"
+ "public\n"
+ " void f() {}\n"
+ "};");
+ verifyFormat("public\n"
+ "int qwerty;");
+ verifyFormat("public\n"
+ "B {}");
+ verifyFormat("public\n"
+ "{\n"
+ "}");
+ verifyFormat("public\n"
+ "B { int x; }");
+}
+
+TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
+ verifyFormat("{");
+ verifyFormat("#})");
+ verifyNoCrash("(/**/[:!] ?[).");
+ verifyNoCrash("struct X {\n"
+ " operator iunt(\n"
+ "};");
+ verifyNoCrash("struct Foo {\n"
+ " operator foo(bar\n"
+ "};");
+ verifyNoCrash("decltype( {\n"
+ " {");
+}
+
+TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
+ // Found by oss-fuzz:
+ // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
+ FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+ Style.ColumnLimit = 60;
+ verifyNoCrash(
+ "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
+ "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
+ "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
+ Style);
+}
+
+TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
+ verifyFormat("do {\n}");
+ verifyFormat("do {\n}\n"
+ "f();");
+ verifyFormat("do {\n}\n"
+ "wheeee(fun);");
+ verifyFormat("do {\n"
+ " f();\n"
+ "}");
+}
+
+TEST_F(FormatTest, IncorrectCodeMissingParens) {
+ verifyFormat("if {\n foo;\n foo();\n}");
+ verifyFormat("switch {\n foo;\n foo();\n}");
+ verifyIncompleteFormat("for {\n foo;\n foo();\n}");
+ verifyIncompleteFormat("ERROR: for target;");
+ verifyFormat("while {\n foo;\n foo();\n}");
+ verifyFormat("do {\n foo;\n foo();\n} while;");
+}
+
+TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
+ verifyIncompleteFormat("namespace {\n"
+ "class Foo { Foo (\n"
+ "};\n"
+ "} // namespace");
+}
+
+TEST_F(FormatTest, IncorrectCodeErrorDetection) {
+ verifyFormat("{\n"
+ " {\n"
+ " }",
+ "{\n"
+ "{\n"
+ "}");
+ verifyFormat("{\n"
+ " {\n"
+ " }",
+ "{\n"
+ " {\n"
+ "}");
+ verifyFormat("{\n"
+ " {\n"
+ " }");
+ verifyFormat("{\n"
+ " {\n"
+ " }\n"
+ "}\n"
+ "}",
+ "{\n"
+ " {\n"
+ " }\n"
+ " }\n"
+ "}");
+
+ verifyFormat("{\n"
+ " {\n"
+ " breakme(\n"
+ " qwe);\n"
+ " }",
+ "{\n"
+ " {\n"
+ " breakme(qwe);\n"
+ "}",
+ getLLVMStyleWithColumns(10));
+}
+
+TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
+ verifyFormat("int x = {\n"
+ " avariable,\n"
+ " b(alongervariable)};",
+ getLLVMStyleWithColumns(25));
+}
+
+TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
+ verifyFormat("return (a)(b){1, 2, 3};");
+}
+
+TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
+ verifyFormat("vector<int> x{1, 2, 3, 4};");
+ verifyFormat("vector<int> x{\n"
+ " 1,\n"
+ " 2,\n"
+ " 3,\n"
+ " 4,\n"
+ "};");
+ verifyFormat("vector<T> x{{}, {}, {}, {}};");
+ verifyFormat("f({1, 2});");
+ verifyFormat("auto v = Foo{-1};");
+ verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
+ verifyFormat("Class::Class : member{1, 2, 3} {}");
+ verifyFormat("new vector<int>{1, 2, 3};");
+ verifyFormat("new int[3]{1, 2, 3};");
+ verifyFormat("new int{1};");
+ verifyFormat("return {arg1, arg2};");
+ verifyFormat("return {arg1, SomeType{parameter}};");
+ verifyFormat("int count = set<int>{f(), g(), h()}.size();");
+ verifyFormat("new T{arg1, arg2};");
+ verifyFormat("f(MyMap[{composite, key}]);");
+ verifyFormat("class Class {\n"
+ " T member = {arg1, arg2};\n"
+ "};");
+ verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
+ verifyFormat("const struct A a = {.a = 1, .b = 2};");
+ verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
+ verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
+ verifyFormat("int a = std::is_integral<int>{} + 0;");
+
+ verifyFormat("int foo(int i) { return fo1{}(i); }");
+ verifyFormat("int foo(int i) { return fo1{}(i); }");
+ verifyFormat("auto i = decltype(x){};");
+ verifyFormat("auto i = typeof(x){};");
+ verifyFormat("auto i = _Atomic(x){};");
+ verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
+ verifyFormat("Node n{1, Node{1000}, //\n"
+ " 2};");
+ verifyFormat("Aaaa aaaaaaa{\n"
+ " {\n"
+ " aaaa,\n"
+ " },\n"
+ "};");
+ verifyFormat("class C : public D {\n"
+ " SomeClass SC{2};\n"
+ "};");
+ verifyFormat("class C : public A {\n"
+ " class D : public B {\n"
+ " void f() { int i{2}; }\n"
+ " };\n"
+ "};");
+ verifyFormat("#define A {a, a},");
+ // Don't confuse braced list initializers with compound statements.
+ verifyFormat(
+ "class A {\n"
+ " A() : a{} {}\n"
+ " A() : Base<int>{} {}\n"
+ " A() : Base<Foo<int>>{} {}\n"
+ " A(int b) : b(b) {}\n"
+ " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
+ " int a, b;\n"
+ " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
+ " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
+ "{}\n"
+ "};");
+
+ // Avoid breaking between equal sign and opening brace
+ FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+ AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+ verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
+ " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
+ " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
+ " {\"ccccccccccccccccccccc\", 2}};",
+ AvoidBreakingFirstArgument);
+
+ // Binpacking only if there is no trailing comma
+ verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
+ " cccccccccc, dddddddddd};",
+ getLLVMStyleWithColumns(50));
+ verifyFormat("const Aaaaaa aaaaa = {\n"
+ " aaaaaaaaaaa,\n"
+ " bbbbbbbbbbb,\n"
+ " ccccccccccc,\n"
+ " ddddddddddd,\n"
+ "};",
+ getLLVMStyleWithColumns(50));
+
+ // Cases where distinguising braced lists and blocks is hard.
+ verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
+ verifyFormat("void f() {\n"
+ " return; // comment\n"
+ "}\n"
+ "SomeType t;");
+ verifyFormat("void f() {\n"
+ " if (a) {\n"
+ " f();\n"
+ " }\n"
+ "}\n"
+ "SomeType t;");
+
+ // In combination with BinPackArguments = false.
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackArguments = false;
+ verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ " iiiiii,\n"
+ " jjjjjj,\n"
+ " kkkkkk};",
+ NoBinPacking);
+ verifyFormat("const Aaaaaa aaaaa = {\n"
+ " aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ " iiiiii,\n"
+ " jjjjjj,\n"
+ " kkkkkk,\n"
+ "};",
+ NoBinPacking);
+ verifyFormat(
+ "const Aaaaaa aaaaa = {\n"
+ " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n"
+ " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n"
+ " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
+ "};",
+ NoBinPacking);
+
+ NoBinPacking.BinPackLongBracedList = false;
+ verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ " iiiiii,\n"
+ " jjjjjj,\n"
+ " kkkkkk,\n"
+ " aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ " iiiiii};",
+ NoBinPacking);
+ verifyFormat("const Aaaaaa aaaaa = {\n"
+ " aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ " iiiiii,\n"
+ " jjjjjj,\n"
+ " kkkkkk,\n"
+ " aaaaa,\n"
+ " bbbbb,\n"
+ " ccccc,\n"
+ " ddddd,\n"
+ " eeeee,\n"
+ " ffffff,\n"
+ " ggggg,\n"
+ " hhhhhh,\n"
+ "};",
+ NoBinPacking);
+
+ NoBinPacking.BreakAfterOpenBracketBracedList = true;
+ verifyFormat("static uint8 CddDp83848Reg[] = {\n"
+ " CDDDP83848_BMCR_REGISTER,\n"
+ " CDDDP83848_BMSR_REGISTER,\n"
+ " CDDDP83848_RBR_REGISTER};",
+ "static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
+ " CDDDP83848_BMSR_REGISTER,\n"
+ " CDDDP83848_RBR_REGISTER};",
+ NoBinPacking);
+
+ // FIXME: The alignment of these trailing comments might be bad. Then again,
+ // this might be utterly useless in real code.
+ verifyFormat("Constructor::Constructor()\n"
+ " : some_value{ //\n"
+ " aaaaaaa, //\n"
+ " bbbbbbb} {}");
+
+ // In braced lists, the first comment is always assumed to belong to the
+ // first element. Thus, it can be moved to the next or previous line as
+ // appropriate.
+ verifyFormat("function({// First element:\n"
+ " 1,\n"
+ " // Second element:\n"
+ " 2});",
+ "function({\n"
+ " // First element:\n"
+ " 1,\n"
+ " // Second element:\n"
+ " 2});");
+ verifyFormat("std::vector<int> MyNumbers{\n"
+ " // First element:\n"
+ " 1,\n"
+ " // Second element:\n"
+ " 2};",
+ "std::vector<int> MyNumbers{// First element:\n"
+ " 1,\n"
+ " // Second element:\n"
+ " 2};",
+ getLLVMStyleWithColumns(30));
+ // A trailing comma should still lead to an enforced line break and no
+ // binpacking.
+ verifyFormat("vector<int> SomeVector = {\n"
+ " // aaa\n"
+ " 1,\n"
+ " 2,\n"
+ "};",
+ "vector<int> SomeVector = { // aaa\n"
+ " 1, 2, };");
+
+ // C++11 brace initializer list l-braces should not be treated any differently
+ // when breaking before lambda bodies is enabled
+ FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
+ BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
+ BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
+ BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
+ verifyFormat(
+ "std::runtime_error{\n"
+ " \"Long string which will force a break onto the next line...\"};",
+ BreakBeforeLambdaBody);
+
+ FormatStyle ExtraSpaces = getLLVMStyle();
+ ExtraSpaces.Cpp11BracedListStyle = FormatStyle::BLS_Block;
+ ExtraSpaces.ColumnLimit = 75;
+ verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
+ verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
+ verifyFormat("f({ 1, 2 });", ExtraSpaces);
+ verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
+ verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
+ verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
+ verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
+ verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
+ verifyFormat("return { arg1, arg2 };", ExtraSpaces);
+ verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
+ verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
+ verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
+ verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
+ verifyFormat("class Class {\n"
+ " T member = { arg1, arg2 };\n"
+ "};",
+ ExtraSpaces);
+ verifyFormat(
+ "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
+ " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " bbbbbbbbbbbbbbbbbbbb, bbbbb };",
+ ExtraSpaces);
+ verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
+ verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
+ ExtraSpaces);
+ verifyFormat(
+ "someFunction(OtherParam,\n"
+ " BracedList{ // comment 1 (Forcing interesting break)\n"
+ " param1, param2,\n"
+ " // comment 2\n"
+ " param3, param4 });",
+ ExtraSpaces);
+ verifyFormat(
+ "std::this_thread::sleep_for(\n"
+ " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
+ ExtraSpaces);
+ verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
+ " aaaaaaa,\n"
+ " aaaaaaaaaa,\n"
+ " aaaaa,\n"
+ " aaaaaaaaaaaaaaa,\n"
+ " aaa,\n"
+ " aaaaaaaaaa,\n"
+ " a,\n"
+ " aaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaa,\n"
+ " a};");
+ verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
+ verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
+ verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
+
+ // Avoid breaking between initializer/equal sign and opening brace
+ ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
+ verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
+ " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
+ " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
+ " { \"ccccccccccccccccccccc\", 2 }\n"
+ "};",
+ ExtraSpaces);
+ verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
+ " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
+ " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
+ " { \"ccccccccccccccccccccc\", 2 }\n"
+ "};",
+ ExtraSpaces);
+
+ FormatStyle SpaceBeforeBrace = getLLVMStyle();
+ SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
+ verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
+ verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
+
+ FormatStyle SpaceBetweenBraces = getLLVMStyle();
+ SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
+ SpaceBetweenBraces.SpacesInParens = FormatStyle::SIPO_Custom;
+ SpaceBetweenBraces.SpacesInParensOptions.Other = true;
+ SpaceBetweenBraces.SpacesInSquareBrackets = true;
+ verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
+ verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
+ verifyFormat("vector< int > x{ // comment 1\n"
+ " 1, 2, 3, 4 };",
+ SpaceBetweenBraces);
+ SpaceBetweenBraces.ColumnLimit = 20;
+ verifyFormat("vector< int > x{\n"
+ " 1, 2, 3, 4 };",
+ "vector<int>x{1,2,3,4};", SpaceBetweenBraces);
+ SpaceBetweenBraces.ColumnLimit = 24;
+ verifyFormat("vector< int > x{ 1, 2,\n"
+ " 3, 4 };",
+ "vector<int>x{1,2,3,4};", SpaceBetweenBraces);
+ verifyFormat("vector< int > x{\n"
+ " 1,\n"
+ " 2,\n"
+ " 3,\n"
+ " 4,\n"
+ "};",
+ "vector<int>x{1,2,3,4,};", SpaceBetweenBraces);
+ verifyFormat("vector< int > x{};", SpaceBetweenBraces);
+ SpaceBetweenBraces.SpacesInParens = FormatStyle::SIPO_Custom;
+ SpaceBetweenBraces.SpacesInParensOptions.InEmptyParentheses = true;
+ verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
+}
+
+TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
+ verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777};");
+ verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, //\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777};");
+ verifyFormat(
+ "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, // comment\n"
+ " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
+ " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
+ " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
+ " 7777777};");
+ verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
+ " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
+ " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
+ verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
+ " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
+ " // Separating comment.\n"
+ " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
+ verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
+ " // Leading comment\n"
+ " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
+ " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
+ verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
+ " 1, 1, 1, 1};",
+ getLLVMStyleWithColumns(39));
+ verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
+ " 1, 1, 1, 1};",
+ getLLVMStyleWithColumns(38));
+ verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
+ getLLVMStyleWithColumns(43));
+ verifyFormat(
+ "static unsigned SomeValues[10][3] = {\n"
+ " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n"
+ " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
+ verifyFormat("static auto fields = new vector<string>{\n"
+ " \"aaaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaa\",\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
+ "};");
+ verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
+ verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
+ " 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
+ " 3, cccccccccccccccccccccc};",
+ getLLVMStyleWithColumns(60));
+
+ // Trailing commas.
+ verifyFormat("vector<int> x = {\n"
+ " 1, 1, 1, 1, 1, 1, 1, 1,\n"
+ "};",
+ getLLVMStyleWithColumns(39));
+ verifyFormat("vector<int> x = {\n"
+ " 1, 1, 1, 1, 1, 1, 1, 1, //\n"
+ "};",
+ getLLVMStyleWithColumns(39));
+ verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
+ " 1, 1, 1, 1,\n"
+ " /**/ /**/};",
+ getLLVMStyleWithColumns(39));
+
+ // Trailing comment in the first line.
+ verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n"
+ " 1111111111, 2222222222, 33333333333, 4444444444, //\n"
+ " 111111111, 222222222, 3333333333, 444444444, //\n"
+ " 11111111, 22222222, 333333333, 44444444};");
+ // Trailing comment in the last line.
+ verifyFormat("int aaaaa[] = {\n"
+ " 1, 2, 3, // comment\n"
+ " 4, 5, 6 // comment\n"
+ "};");
+
+ // With nested lists, we should either format one item per line or all nested
+ // lists one on line.
+ // FIXME: For some nested lists, we can do better.
+ verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
+ " {aaaaaaaaaaaaaaaaaaa},\n"
+ " {aaaaaaaaaaaaaaaaaaaaa},\n"
+ " {aaaaaaaaaaaaaaaaa}};",
+ getLLVMStyleWithColumns(60));
+ verifyFormat(
+ "SomeStruct my_struct_array = {\n"
+ " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
+ " aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
+ " {aaa, aaa},\n"
+ " {aaa, aaa},\n"
+ " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
+ " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
+
+ // No column layout should be used here.
+ verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
+
+ verifyNoCrash("a<,");
+
+ // No braced initializer here.
+ verifyFormat("void f() {\n"
+ " struct Dummy {};\n"
+ " f(v);\n"
+ "}");
+ verifyFormat("void foo() {\n"
+ " { // asdf\n"
+ " {\n"
+ " int a;\n"
+ " }\n"
+ " }\n"
+ " {\n"
+ " {\n"
+ " int b;\n"
+ " }\n"
+ " }\n"
+ "}");
+ verifyFormat("namespace n {\n"
+ "void foo() {\n"
+ " {\n"
+ " {\n"
+ " statement();\n"
+ " if (false) {\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " {\n"
+ " }\n"
+ "}\n"
+ "} // namespace n");
+
+ // Long lists should be formatted in columns even if they are nested.
+ verifyFormat(
+ "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777});");
+
+ // Allow "single-column" layout even if that violates the column limit. There
+ // isn't going to be a better way.
+ verifyFormat("std::vector<int> a = {\n"
+ " aaaaaaaa,\n"
+ " aaaaaaaa,\n"
+ " aaaaaaaa,\n"
+ " aaaaaaaa,\n"
+ " aaaaaaaaaa,\n"
+ " aaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
+ getLLVMStyleWithColumns(30));
+ verifyFormat("vector<int> aaaa = {\n"
+ " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaa.aaaaaaa,\n"
+ " aaaaaa.aaaaaaa,\n"
+ " aaaaaa.aaaaaaa,\n"
+ " aaaaaa.aaaaaaa,\n"
+ "};");
+
+ // Don't create hanging lists.
+ verifyFormat("someFunction(Param, {List1, List2,\n"
+ " List3});",
+ getLLVMStyleWithColumns(35));
+ verifyFormat("someFunction(Param, Param,\n"
+ " {List1, List2,\n"
+ " List3});",
+ getLLVMStyleWithColumns(35));
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa);");
+
+ // No possible column formats, don't want the optimal paths penalized.
+ verifyFormat(
+ "waarudo::unit desk = {\n"
+ " .s = \"desk\", .p = p, .b = [] { return w::r{3, 10} * w::m; }};");
+ verifyFormat("SomeType something1([](const Input &i) -> Output { return "
+ "Output{1, 2}; },\n"
+ " [](const Input &i) -> Output { return "
+ "Output{1, 2}; });");
+ FormatStyle NoBinPacking = getLLVMStyle();
+ NoBinPacking.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("waarudo::unit desk = {\n"
+ " .s = \"desk\", .p = p, .b = [] { return w::r{3, 10, 1, 1, "
+ "1, 1} * w::m; }};",
+ NoBinPacking);
+}
+
+TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
+ FormatStyle DoNotMerge = getLLVMStyle();
+ DoNotMerge.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle();
+
+ verifyFormat("void f() { return 42; }");
+ verifyFormat("void f() {\n"
+ " return 42;\n"
+ "}",
+ DoNotMerge);
+ verifyFormat("void f() {\n"
+ " // Comment\n"
+ "}");
+ verifyFormat("{\n"
+ "#error {\n"
+ " int a;\n"
+ "}");
+ verifyFormat("{\n"
+ " int a;\n"
+ "#error {\n"
+ "}");
+ verifyFormat("void f() {} // comment");
+ verifyFormat("void f() { int a; } // comment");
+ verifyFormat("void f() {\n"
+ "} // comment",
+ DoNotMerge);
+ verifyFormat("void f() {\n"
+ " int a;\n"
+ "} // comment",
+ DoNotMerge);
+ verifyFormat("void f() {\n"
+ "} // comment",
+ getLLVMStyleWithColumns(15));
+
+ verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
+ verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22));
+
+ verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
+ verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
+ verifyGoogleFormat("class C {\n"
+ " C()\n"
+ " : iiiiiiii(nullptr),\n"
+ " kkkkkkk(nullptr),\n"
+ " mmmmmmm(nullptr),\n"
+ " nnnnnnn(nullptr) {}\n"
+ "};");
+
+ FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
+ verifyFormat("A() : b(0) {}", "A():b(0){}", NoColumnLimit);
+ verifyFormat("class C {\n"
+ " A() : b(0) {}\n"
+ "};",
+ "class C{A():b(0){}};", NoColumnLimit);
+ verifyFormat("A()\n"
+ " : b(0) {\n"
+ "}",
+ "A()\n:b(0)\n{\n}", NoColumnLimit);
+
+ FormatStyle NoColumnLimitWrapAfterFunction = NoColumnLimit;
+ NoColumnLimitWrapAfterFunction.BreakBeforeBraces = FormatStyle::BS_Custom;
+ NoColumnLimitWrapAfterFunction.BraceWrapping.AfterFunction = true;
+ verifyFormat("class C {\n"
+ "#pragma foo\n"
+ " int foo { return 0; }\n"
+ "};",
+ NoColumnLimitWrapAfterFunction);
+ verifyFormat("class C {\n"
+ "#pragma foo\n"
+ " void foo {}\n"
+ "};",
+ NoColumnLimitWrapAfterFunction);
+
+ FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
+ DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle();
+ verifyFormat("A() : b(0) {\n"
+ "}",
+ DoNotMergeNoColumnLimit);
+ verifyNoChange("A()\n"
+ " : b(0) {\n"
+ "}",
+ DoNotMergeNoColumnLimit);
+ verifyFormat("A()\n"
+ " : b(0) {\n"
+ "}",
+ "A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit);
+
+ verifyFormat("#define A \\\n"
+ " void f() { \\\n"
+ " int i; \\\n"
+ " }",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("#define A \\\n"
+ " void f() { int i; }",
+ getLLVMStyleWithColumns(21));
+ verifyFormat("#define A \\\n"
+ " void f() { \\\n"
+ " int i; \\\n"
+ " } \\\n"
+ " int j;",
+ getLLVMStyleWithColumns(22));
+ verifyFormat("#define A \\\n"
+ " void f() { int i; } \\\n"
+ " int j;",
+ getLLVMStyleWithColumns(23));
+
+ verifyFormat(
+ "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {}");
+
+ constexpr StringRef Code("void foo() { /* Empty */ }");
+ verifyFormat(Code);
+ verifyFormat(Code, "void foo() { /* Empty */\n"
+ "}");
+ verifyFormat(Code, "void foo() {\n"
+ "/* Empty */\n"
+ "}");
+}
+
+TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
+ FormatStyle MergeEmptyOnly = getLLVMStyle();
+ MergeEmptyOnly.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeEmptyOnly);
+ verifyFormat("class C {\n"
+ " int f() {\n"
+ " return 42;\n"
+ " }\n"
+ "};",
+ MergeEmptyOnly);
+ verifyFormat("int f() {}", MergeEmptyOnly);
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ MergeEmptyOnly);
+
+ // Also verify behavior when BraceWrapping.AfterFunction = true
+ MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
+ MergeEmptyOnly.BraceWrapping.AfterFunction = true;
+ verifyFormat("int f() {}", MergeEmptyOnly);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeEmptyOnly);
+}
+
+TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
+ FormatStyle MergeInlineOnly = getLLVMStyle();
+ MergeInlineOnly.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ MergeInlineOnly);
+
+ // SFS_Inline implies SFS_Empty
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f() {}", MergeInlineOnly);
+ // https://llvm.org/PR54147
+ verifyFormat("auto lambda = []() {\n"
+ " // comment\n"
+ " f();\n"
+ " g();\n"
+ "};",
+ MergeInlineOnly);
+
+ verifyFormat("class C {\n"
+ "#ifdef A\n"
+ " int f() { return 42; }\n"
+ "#endif\n"
+ "};",
+ MergeInlineOnly);
+
+ verifyFormat("struct S {\n"
+ "// comment\n"
+ "#ifdef FOO\n"
+ " int foo() { bar(); }\n"
+ "#endif\n"
+ "};",
+ MergeInlineOnly);
+
+ MergeInlineOnly.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ verifyFormat("#define Foo \\\n"
+ " struct S { \\\n"
+ " void foo() { return; } \\\n"
+ " }",
+ MergeInlineOnly);
+
+ // Also verify behavior when BraceWrapping.AfterFunction = true
+ MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
+ MergeInlineOnly.BraceWrapping.AfterFunction = true;
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f()\n"
+ "{\n"
+ " return 42;\n"
+ "}",
+ MergeInlineOnly);
+
+ // SFS_Inline implies SFS_Empty
+ verifyFormat("int f() {}", MergeInlineOnly);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeInlineOnly);
+
+ MergeInlineOnly.BraceWrapping.AfterClass = true;
+ MergeInlineOnly.BraceWrapping.AfterStruct = true;
+ verifyFormat("class C\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("struct C\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f()\n"
+ "{\n"
+ " return 42;\n"
+ "}",
+ MergeInlineOnly);
+ verifyFormat("int f() {}", MergeInlineOnly);
+ verifyFormat("class C\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("struct C\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("struct C\n"
+ "// comment\n"
+ "/* comment */\n"
+ "// comment\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("/* comment */ struct C\n"
+ "{\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+}
+
+TEST_F(FormatTest, CustomShortFunctionOptions) {
+ FormatStyle CustomEmpty = getLLVMStyle();
+ CustomEmpty.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+
+ // Empty functions should be on a single line
+ verifyFormat("int f() {}", CustomEmpty);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ CustomEmpty);
+
+ // Non-empty functions should be multi-line
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ CustomEmpty);
+ verifyFormat("class C {\n"
+ " int f() {\n"
+ " return 42;\n"
+ " }\n"
+ "};",
+ CustomEmpty);
+
+ // test with comment
+ verifyFormat("void f3() { /* comment */ }", CustomEmpty);
+
+ // Test with AfterFunction = true
+ CustomEmpty.BreakBeforeBraces = FormatStyle::BS_Custom;
+ CustomEmpty.BraceWrapping.AfterFunction = true;
+ verifyFormat("int f() {}", CustomEmpty);
+ verifyFormat("int g()\n"
+ "{\n"
+ " return 42;\n"
+ "}",
+ CustomEmpty);
+
+ // Test with Inline = true, All = false
+ FormatStyle CustomInline = getLLVMStyle();
+ CustomInline.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setInlineOnly();
+
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ CustomInline);
+
+ // Non-empty inline functions should be single-line
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ CustomInline);
+
+ // Non-inline functions should be multi-line
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ CustomInline);
+ verifyFormat("int g() {\n"
+ "}",
+ CustomInline);
+
+ // Test with All = true
+ FormatStyle CustomAll = getLLVMStyle();
+ CustomAll.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+
+ // All functions should be on a single line if they fit
+ verifyFormat("int f() { return 42; }", CustomAll);
+ verifyFormat("int g() { return f() + h(); }", CustomAll);
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ CustomAll);
+
+ verifyFormat("int f() {}", CustomAll);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ CustomAll);
+
+ // Test various combinations
+ FormatStyle CustomMixed = getLLVMStyle();
+ CustomMixed.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+
+ // Empty functions should be on a single line
+ verifyFormat("int f() {}", CustomMixed);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ CustomMixed);
+
+ // Inline non-empty functions should be on a single line
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ CustomMixed);
+
+ // Non-inline non-empty functions should be multi-line
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ CustomMixed);
+}
+
+TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
+ FormatStyle MergeInlineOnly = getLLVMStyle();
+ MergeInlineOnly.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setInlineOnly();
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f() {\n"
+ " return 42;\n"
+ "}",
+ MergeInlineOnly);
+
+ // SFS_InlineOnly does not imply SFS_Empty
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f() {\n"
+ "}",
+ MergeInlineOnly);
+
+ MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
+ verifyFormat("class Foo\n"
+ " {\n"
+ " void f() { foo(); }\n"
+ " };",
+ MergeInlineOnly);
+
+ // Also verify behavior when BraceWrapping.AfterFunction = true
+ MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
+ MergeInlineOnly.BraceWrapping.AfterFunction = true;
+ verifyFormat("class C {\n"
+ " int f() { return 42; }\n"
+ "};",
+ MergeInlineOnly);
+ verifyFormat("int f()\n"
+ "{\n"
+ " return 42;\n"
+ "}",
+ MergeInlineOnly);
+
+ // SFS_InlineOnly does not imply SFS_Empty
+ verifyFormat("int f()\n"
+ "{\n"
+ "}",
+ MergeInlineOnly);
+ verifyFormat("class C {\n"
+ " int f() {}\n"
+ "};",
+ MergeInlineOnly);
+}
+
+TEST_F(FormatTest, SplitEmptyFunction) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ Style.BraceWrapping.SplitEmptyFunction = false;
+
+ verifyFormat("int f()\n"
+ "{}",
+ Style);
+ verifyFormat("int f()\n"
+ "{\n"
+ " return 42;\n"
+ "}",
+ Style);
+ verifyFormat("int f()\n"
+ "{\n"
+ " // some comment\n"
+ "}",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ verifyFormat("int f() {}", Style);
+ verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
+ "{}",
+ Style);
+ verifyFormat("int f()\n"
+ "{\n"
+ " return 0;\n"
+ "}",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyAndInline();
+ verifyFormat("class Foo {\n"
+ " int f() {}\n"
+ "};",
+ Style);
+ verifyFormat("class Foo {\n"
+ " int f() { return 0; }\n"
+ "};",
+ Style);
+ verifyFormat("class Foo {\n"
+ " int f() { return 0; }\n"
+ "};",
+ Style);
+ verifyFormat("class Foo {\n"
+ " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
+ " {}\n"
+ "};",
+ Style);
+ verifyFormat("class Foo {\n"
+ " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
+ " {\n"
+ " return 0;\n"
+ " }\n"
+ "};",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ verifyFormat("int f() {}", Style);
+ verifyFormat("int f() { return 0; }", Style);
+ verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
+ "{}",
+ Style);
+ verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
+ "{\n"
+ " return 0;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+ Style.BraceWrapping.SplitEmptyFunction = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("class C {};", Style);
+ verifyFormat("struct C {};", Style);
+ verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
+ "{\n"
+ "}",
+ Style);
+ verifyFormat("class C {\n"
+ " C()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
+ " bbbbbbbbbbbbbbbbbbb()\n"
+ " {\n"
+ " }\n"
+ " void\n"
+ " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
+ " {\n"
+ " }\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, MergeShortFunctionBody) {
+ auto Style = getLLVMStyle();
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+
+ verifyFormat("int foo()\n"
+ "{ return 1; }",
+ Style);
+}
+
+TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
+ FormatStyle Style = getLLVMStyle();
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ verifyFormat("#ifdef A\n"
+ "int f() {}\n"
+ "#else\n"
+ "int g() {}\n"
+ "#endif",
+ Style);
+}
+
+TEST_F(FormatTest, SplitEmptyClass) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("class Foo\n"
+ "{};",
+ Style);
+ verifyFormat("/* something */ class Foo\n"
+ "{};",
+ Style);
+ verifyFormat("template <typename X> class Foo\n"
+ "{};",
+ Style);
+ verifyFormat("class Foo\n"
+ "{\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef class Foo\n"
+ "{\n"
+ "} Foo_t;",
+ Style);
+
+ Style.BraceWrapping.SplitEmptyRecord = true;
+ Style.BraceWrapping.AfterStruct = true;
+ verifyFormat("class rep\n"
+ "{\n"
+ "};",
+ Style);
+ verifyFormat("struct rep\n"
+ "{\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> class rep\n"
+ "{\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> struct rep\n"
+ "{\n"
+ "};",
+ Style);
+ verifyFormat("class rep\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("struct rep\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> class rep\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> struct rep\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> class rep // Foo\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> struct rep // Bar\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+
+ verifyFormat("template <typename T> class rep<T>\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+
+ verifyFormat("template <typename T> class rep<std::complex<T>>\n"
+ "{\n"
+ " int x;\n"
+ "};",
+ Style);
+ verifyFormat("template <typename T> class rep<std::complex<T>>\n"
+ "{\n"
+ "};",
+ Style);
+
+ verifyFormat("#include \"stdint.h\"\n"
+ "namespace rep {}",
+ Style);
+ verifyFormat("#include <stdint.h>\n"
+ "namespace rep {}",
+ Style);
+ verifyFormat("#include <stdint.h>\n"
+ "namespace rep {}",
+ "#include <stdint.h>\n"
+ "namespace rep {\n"
+ "\n"
+ "\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, SplitEmptyStruct) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterStruct = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("struct Foo\n"
+ "{};",
+ Style);
+ verifyFormat("/* something */ struct Foo\n"
+ "{};",
+ Style);
+ verifyFormat("template <typename X> struct Foo\n"
+ "{};",
+ Style);
+ verifyFormat("struct Foo\n"
+ "{\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef struct Foo\n"
+ "{\n"
+ "} Foo_t;",
+ Style);
+ // typedef struct Bar {} Bar_t;
+}
+
+TEST_F(FormatTest, SplitEmptyUnion) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterUnion = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("union Foo\n"
+ "{};",
+ Style);
+ verifyFormat("/* something */ union Foo\n"
+ "{};",
+ Style);
+ verifyFormat("union Foo\n"
+ "{\n"
+ " A,\n"
+ "};",
+ Style);
+ verifyFormat("typedef union Foo\n"
+ "{\n"
+ "} Foo_t;",
+ Style);
+}
+
+TEST_F(FormatTest, SplitEmptyNamespace) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterNamespace = true;
+ Style.BraceWrapping.SplitEmptyNamespace = false;
+
+ verifyFormat("namespace Foo\n"
+ "{};",
+ Style);
+ verifyFormat("/* something */ namespace Foo\n"
+ "{};",
+ Style);
+ verifyFormat("inline namespace Foo\n"
+ "{};",
+ Style);
+ verifyFormat("/* something */ inline namespace Foo\n"
+ "{};",
+ Style);
+ verifyFormat("export namespace Foo\n"
+ "{};",
+ Style);
+ verifyFormat("namespace Foo\n"
+ "{\n"
+ "void Bar();\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, NeverMergeShortRecords) {
+ FormatStyle Style = getLLVMStyle();
+
+ verifyFormat("class Foo {\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef class Foo {\n"
+ " Foo();\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("struct Foo {\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef struct Foo {\n"
+ " Foo();\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("union Foo {\n"
+ " A,\n"
+ "};",
+ Style);
+ verifyFormat("typedef union Foo {\n"
+ " A,\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("namespace Foo {\n"
+ "void Bar();\n"
+ "};",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ Style.BraceWrapping.AfterStruct = true;
+ Style.BraceWrapping.AfterUnion = true;
+ Style.BraceWrapping.AfterNamespace = true;
+ verifyFormat("class Foo\n"
+ "{\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef class Foo\n"
+ "{\n"
+ " Foo();\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("struct Foo\n"
+ "{\n"
+ " Foo();\n"
+ "};",
+ Style);
+ verifyFormat("typedef struct Foo\n"
+ "{\n"
+ " Foo();\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("union Foo\n"
+ "{\n"
+ " A,\n"
+ "};",
+ Style);
+ verifyFormat("typedef union Foo\n"
+ "{\n"
+ " A,\n"
+ "} Foo_t;",
+ Style);
+ verifyFormat("namespace Foo\n"
+ "{\n"
+ "void Bar();\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, AllowShortRecordOnASingleLine) {
+ auto Style = getLLVMStyle();
+ EXPECT_EQ(Style.AllowShortRecordOnASingleLine,
+ FormatStyle::SRS_EmptyAndAttached);
+
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Never;
+ verifyFormat("class foo {\n"
+ "};\n"
+ "class bar {\n"
+ " int i;\n"
+ "};",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ verifyFormat("class foo\n"
+ "{\n"
+ "};\n"
+ "class bar\n"
+ "{\n"
+ " int i;\n"
+ "};",
+ Style);
+ Style.BraceWrapping.SplitEmptyRecord = false;
+ verifyFormat("class foo\n"
+ "{};",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Empty;
+ verifyFormat("class foo {};\n"
+ "class bar {\n"
+ " int i;\n"
+ "};",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ verifyFormat("class foo\n"
+ "{\n"
+ "};\n"
+ "class bar\n"
+ "{\n"
+ " int i;\n"
+ "};",
+ Style);
+ Style.BraceWrapping.SplitEmptyRecord = false;
+ verifyFormat("class foo {};", Style);
+
+ Style = getLLVMStyle();
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
+ verifyFormat("class foo {};\n"
+ "class bar { int i; };",
+ Style);
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ verifyFormat("class foo\n"
+ "{\n"
+ "};\n"
+ "class bar { int i; };",
+ Style);
+ Style.BraceWrapping.SplitEmptyRecord = false;
+ verifyFormat("class foo {};", Style);
+
+ Style = getLLVMStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Never;
+ verifyFormat("class foo\n"
+ "{ int i; };",
+ Style);
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Empty;
+ verifyFormat("class foo\n"
+ "{ int i; };",
+ Style);
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
+ verifyFormat("class foo\n"
+ "{\n"
+ "};\n"
+ "class foo { int i; };",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.BraceWrapping.SplitEmptyRecord = false;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterClass = true;
+ Style.AllowShortRecordOnASingleLine = FormatStyle::SRS_Always;
+ verifyFormat("class foo\n"
+ "{\n"
+ " int i;\n"
+ " int j;\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
+ // Elaborate type variable declarations.
+ verifyFormat("struct foo a = {bar};\nint n;");
+ verifyFormat("class foo a = {bar};\nint n;");
+ verifyFormat("union foo a = {bar};\nint n;");
+
+ // Elaborate types inside function definitions.
+ verifyFormat("struct foo f() {}\nint n;");
+ verifyFormat("class foo f() {}\nint n;");
+ verifyFormat("union foo f() {}\nint n;");
+
+ // Templates.
+ verifyFormat("template <class X> void f() {}\nint n;");
+ verifyFormat("template <struct X> void f() {}\nint n;");
+ verifyFormat("template <union X> void f() {}\nint n;");
+
+ // Actual definitions...
+ verifyFormat("struct {\n} n;");
+ verifyFormat(
+ "template <template <class T, class Y>, class Z> class X {\n} n;");
+ verifyFormat("union Z {\n int n;\n} x;");
+ verifyFormat("class MACRO Z {\n} n;");
+ verifyFormat("class MACRO(X) Z {\n} n;");
+ verifyFormat("class __attribute__((X)) Z {\n} n;");
+ verifyFormat("class __declspec(X) Z {\n} n;");
+ verifyFormat("class A##B##C {\n} n;");
+ verifyFormat("class alignas(16) Z {\n} n;");
+ verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
+ verifyFormat("class MACROA MACRO(X) Z {\n} n;");
+
+ // Redefinition from nested context:
+ verifyFormat("class A::B::C {\n} n;");
+
+ // Template definitions.
+ verifyFormat(
+ "template <typename F>\n"
+ "Matcher(const Matcher<F> &Other,\n"
+ " typename enable_if_c<is_base_of<F, T>::value &&\n"
+ " !is_same<F, T>::value>::type * = 0)\n"
+ " : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
+
+ // FIXME: This is still incorrectly handled at the formatter side.
+ verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
+ verifyFormat("int i = SomeFunction(a<b, a> b);");
+
+ verifyFormat("class A<int> f() {}\n"
+ "int n;");
+ verifyFormat("template <typename T> class A<T> f() {}\n"
+ "int n;");
+
+ verifyFormat("template <> class Foo<int> F() {\n"
+ "} n;");
+
+ // Elaborate types where incorrectly parsing the structural element would
+ // break the indent.
+ verifyFormat("if (true)\n"
+ " class X x;\n"
+ "else\n"
+ " f();");
+
+ // This is simply incomplete. Formatting is not important, but must not crash.
+ verifyFormat("class A:");
+}
+
+TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
+ verifyNoChange("#error Leave all white!!!!! space* alone!");
+ verifyNoChange("#warning Leave all white!!!!! space* alone!");
+ verifyFormat("#error 1", " # error 1");
+ verifyFormat("#warning 1", " # warning 1");
+}
+
+TEST_F(FormatTest, FormatHashIfExpressions) {
+ verifyFormat("#if AAAA && BBBB");
+ verifyFormat("#if (AAAA && BBBB)");
+ verifyFormat("#elif (AAAA && BBBB)");
+ // FIXME: Come up with a better indentation for #elif.
+ verifyFormat(
+ "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n"
+ " defined(BBBBBBBB)\n"
+ "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n"
+ " defined(BBBBBBBB)\n"
+ "#endif",
+ getLLVMStyleWithColumns(65));
+}
+
+TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
+ FormatStyle AllowsMergedIf = getGoogleStyle();
+ AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
+ verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
+ verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf);
+ verifyFormat("if (true) return 42;", "if (true)\nreturn 42;", AllowsMergedIf);
+ FormatStyle ShortMergedIf = AllowsMergedIf;
+ ShortMergedIf.ColumnLimit = 25;
+ verifyFormat("#define A \\\n"
+ " if (true) return 42;",
+ ShortMergedIf);
+ verifyFormat("#define A \\\n"
+ " f(); \\\n"
+ " if (true)\n"
+ "#define B",
+ ShortMergedIf);
+ verifyFormat("#define A \\\n"
+ " f(); \\\n"
+ " if (true)\n"
+ "g();",
+ ShortMergedIf);
+ verifyFormat("{\n"
+ "#ifdef A\n"
+ " // Comment\n"
+ " if (true) continue;\n"
+ "#endif\n"
+ " // Comment\n"
+ " if (true) continue;\n"
+ "}",
+ ShortMergedIf);
+ ShortMergedIf.ColumnLimit = 33;
+ verifyFormat("#define A \\\n"
+ " if constexpr (true) return 42;",
+ ShortMergedIf);
+ verifyFormat("#define A \\\n"
+ " if CONSTEXPR (true) return 42;",
+ ShortMergedIf);
+ ShortMergedIf.ColumnLimit = 29;
+ verifyFormat("#define A \\\n"
+ " if (aaaaaaaaaa) return 1; \\\n"
+ " return 2;",
+ ShortMergedIf);
+ ShortMergedIf.ColumnLimit = 28;
+ verifyFormat("#define A \\\n"
+ " if (aaaaaaaaaa) \\\n"
+ " return 1; \\\n"
+ " return 2;",
+ ShortMergedIf);
+ verifyFormat("#define A \\\n"
+ " if constexpr (aaaaaaa) \\\n"
+ " return 1; \\\n"
+ " return 2;",
+ ShortMergedIf);
+ verifyFormat("#define A \\\n"
+ " if CONSTEXPR (aaaaaaa) \\\n"
+ " return 1; \\\n"
+ " return 2;",
+ ShortMergedIf);
+
+ verifyFormat("//\n"
+ "#define a \\\n"
+ " if \\\n"
+ " 0",
+ getChromiumStyle(FormatStyle::LK_Cpp));
+}
+
+TEST_F(FormatTest, FormatStarDependingOnContext) {
+ verifyFormat("void f(int *a);");
+ verifyFormat("void f() { f(fint * b); }");
+ verifyFormat("class A {\n void f(int *a);\n};");
+ verifyFormat("class A {\n int *a;\n};");
+ verifyFormat("namespace a {\n"
+ "namespace b {\n"
+ "class A {\n"
+ " void f() {}\n"
+ " int *a;\n"
+ "};\n"
+ "} // namespace b\n"
+ "} // namespace a");
+}
+
+TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
+ verifyFormat("while");
+ verifyFormat("operator");
+}
+
+TEST_F(FormatTest, SkipsDeeplyNestedLines) {
+ // This code would be painfully slow to format if we didn't skip it.
+ std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
+ "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
+ "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
+ "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
+ "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
+ "A(1, 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
+ ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
+ // Deeply nested part is untouched, rest is formatted.
+ EXPECT_EQ(std::string("int i;") + Code + "int j;",
+ format(std::string("int i;") + Code + "int j;",
+ getLLVMStyle(), SC_ExpectIncomplete));
+}
+
+//===----------------------------------------------------------------------===//
+// Objective-C tests.
+//===----------------------------------------------------------------------===//
+
+TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
+ verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
+ verifyFormat("- (NSUInteger)indexOfObject:(id)anObject;",
+ "-(NSUInteger)indexOfObject:(id)anObject;");
+ verifyFormat("- (NSInteger)Mthod1;", "-(NSInteger)Mthod1;");
+ verifyFormat("+ (id)Mthod2;", "+(id)Mthod2;");
+ verifyFormat("- (NSInteger)Method3:(id)anObject;",
+ "-(NSInteger)Method3:(id)anObject;");
+ verifyFormat("- (NSInteger)Method4:(id)anObject;",
+ "-(NSInteger)Method4:(id)anObject;");
+ verifyFormat("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
+ "-(NSInteger)Method5:(id)anObject:(id)AnotherObject;");
+ verifyFormat("- (id)Method6:(id)A:(id)B:(id)C:(id)D;");
+ verifyFormat("- (void)sendAction:(SEL)aSelector to:(id)anObject "
+ "forAllCells:(BOOL)flag;");
+
+ // Very long objectiveC method declaration.
+ verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
+ " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
+ verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
+ " inRange:(NSRange)range\n"
+ " outRange:(NSRange)out_range\n"
+ " outRange1:(NSRange)out_range1\n"
+ " outRange2:(NSRange)out_range2\n"
+ " outRange3:(NSRange)out_range3\n"
+ " outRange4:(NSRange)out_range4\n"
+ " outRange5:(NSRange)out_range5\n"
+ " outRange6:(NSRange)out_range6\n"
+ " outRange7:(NSRange)out_range7\n"
+ " outRange8:(NSRange)out_range8\n"
+ " outRange9:(NSRange)out_range9;");
+
+ // When the function name has to be wrapped.
+ FormatStyle Style = getLLVMStyle();
+ // ObjC ignores IndentWrappedFunctionNames when wrapping methods
+ // and always indents instead.
+ Style.IndentWrappedFunctionNames = false;
+ verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
+ " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
+ " anotherName:(NSString)bbbbbbbbbbbbbb {\n"
+ "}",
+ Style);
+ Style.IndentWrappedFunctionNames = true;
+ verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
+ " veryLooooooooooongName:(NSString)cccccccccccccc\n"
+ " anotherName:(NSString)dddddddddddddd {\n"
+ "}",
+ Style);
+
+ verifyFormat("- (int)sum:(vector<int>)numbers;");
+ verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
+ // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
+ // protocol lists (but not for template classes):
+ // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
+
+ verifyFormat("- (int (*)())foo:(int (*)())f;");
+ verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
+
+ // If there's no return type (very rare in practice!), LLVM and Google style
+ // agree.
+ verifyFormat("- foo;");
+ verifyFormat("- foo:(int)f;");
+ verifyGoogleFormat("- foo:(int)foo;");
+}
+
+TEST_F(FormatTest, SpaceBeforeObjCMethodDeclColon) {
+ auto Style = getLLVMStyle();
+ EXPECT_TRUE(Style.ObjCSpaceAfterMethodDeclarationPrefix);
+ verifyFormat("- (void)method;", Style);
+ Style.ObjCSpaceAfterMethodDeclarationPrefix = false;
+ verifyFormat("-(void)method;", Style);
+}
+
+TEST_F(FormatTest, BreaksStringLiterals) {
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some text \"\n"
+ "\"other\";",
+ format("\"some text other\";", getLLVMStyleWithColumns(12)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some text \"\n"
+ "\"other\";",
+ format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
+ verifyFormat("#define A \\\n"
+ " \"some \" \\\n"
+ " \"text \" \\\n"
+ " \"other\";",
+ "#define A \"some text other\";", getLLVMStyleWithColumns(12));
+ verifyFormat("#define A \\\n"
+ " \"so \" \\\n"
+ " \"text \" \\\n"
+ " \"other\";",
+ "#define A \"so text other\";", getLLVMStyleWithColumns(12));
+
+ verifyFormat("\"some text\"", getLLVMStyleWithColumns(1));
+ verifyFormat("\"some text\"", getLLVMStyleWithColumns(11));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some \"\n"
+ "\"text\"",
+ format("\"some text\"", getLLVMStyleWithColumns(10)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some \"\n"
+ "\"text\"",
+ format("\"some text\"", getLLVMStyleWithColumns(7)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some\"\n"
+ "\" tex\"\n"
+ "\"t\"",
+ format("\"some text\"", getLLVMStyleWithColumns(6)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some\"\n"
+ "\" tex\"\n"
+ "\" and\"",
+ format("\"some tex and\"", getLLVMStyleWithColumns(6)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"some\"\n"
+ "\"/tex\"\n"
+ "\"/and\"",
+ format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
+
+ verifyFormat("variable =\n"
+ " \"long string \"\n"
+ " \"literal\";",
+ "variable = \"long string literal\";",
+ getLLVMStyleWithColumns(20));
+
+ verifyFormat("variable = f(\n"
+ " \"long string \"\n"
+ " \"literal\",\n"
+ " short,\n"
+ " loooooooooooooooooooong);",
+ "variable = f(\"long string literal\", short, "
+ "loooooooooooooooooooong);",
+ getLLVMStyleWithColumns(20));
+
+ verifyFormat("f(g(\"long string \"\n"
+ " \"literal\"),\n"
+ " b);",
+ "f(g(\"long string literal\"), b);",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("f(g(\"long string \"\n"
+ " \"literal\",\n"
+ " a),\n"
+ " b);",
+ "f(g(\"long string literal\", a), b);",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("f(\"one two\".split(\n"
+ " variable));",
+ "f(\"one two\".split(variable));", getLLVMStyleWithColumns(20));
+ verifyFormat("f(\"one two three four five six \"\n"
+ " \"seven\".split(\n"
+ " really_looooong_variable));",
+ "f(\"one two three four five six seven\"."
+ "split(really_looooong_variable));",
+ getLLVMStyleWithColumns(33));
+
+ verifyFormat("f(\"some \"\n"
+ " \"text\",\n"
+ " other);",
+ "f(\"some text\", other);", getLLVMStyleWithColumns(10));
+
+ // Only break as a last resort.
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
+
+ // FIXME: unstable test case
+ EXPECT_EQ("\"splitmea\"\n"
+ "\"trandomp\"\n"
+ "\"oint\"",
+ format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
+
+ // FIXME: unstable test case
+ EXPECT_EQ("\"split/\"\n"
+ "\"pathat/\"\n"
+ "\"slashes\"",
+ format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
+
+ // FIXME: unstable test case
+ EXPECT_EQ("\"split/\"\n"
+ "\"pathat/\"\n"
+ "\"slashes\"",
+ format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"split at \"\n"
+ "\"spaces/at/\"\n"
+ "\"slashes.at.any$\"\n"
+ "\"non-alphanumeric%\"\n"
+ "\"1111111111characte\"\n"
+ "\"rs\"",
+ format("\"split at "
+ "spaces/at/"
+ "slashes.at."
+ "any$non-"
+ "alphanumeric%"
+ "1111111111characte"
+ "rs\"",
+ getLLVMStyleWithColumns(20)));
+
+ // Verify that splitting the strings understands
+ // Style::AlwaysBreakBeforeMultilineStrings.
+ verifyFormat("aaaaaaaaaaaa(\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
+ "aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaa\");",
+ getGoogleStyle());
+ verifyFormat("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
+ "return \"aaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaa\";",
+ getGoogleStyle());
+ verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
+ "llvm::outs() << "
+ "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
+ "aaaaaaaaaaaaaaaaaaa\";");
+ verifyFormat("ffff(\n"
+ " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
+ " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
+ "ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
+ getGoogleStyle());
+
+ FormatStyle Style = getLLVMStyleWithColumns(12);
+ Style.BreakStringLiterals = false;
+ verifyFormat("\"some text other\";", Style);
+
+ FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
+ AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ verifyFormat("#define A \\\n"
+ " \"some \" \\\n"
+ " \"text \" \\\n"
+ " \"other\";",
+ "#define A \"some text other\";", AlignLeft);
+}
+
+TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
+ verifyFormat("C a = \"some more \"\n"
+ " \"text\";",
+ "C a = \"some more text\";", getLLVMStyleWithColumns(18));
+}
+
+TEST_F(FormatTest, FullyRemoveEmptyLines) {
+ FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
+ NoEmptyLines.MaxEmptyLinesToKeep = 0;
+ verifyFormat("int i = a(b());", "int i=a(\n\n b(\n\n\n )\n\n);",
+ NoEmptyLines);
+}
+
+TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ "(\n"
+ " \"x\t\");",
+ format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ "aaaaaaa("
+ "\"x\t\");"));
+}
+
+TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "u8\"utf8 string \"\n"
+ "u8\"literal\";",
+ format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "u\"utf16 string \"\n"
+ "u\"literal\";",
+ format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "U\"utf32 string \"\n"
+ "U\"literal\";",
+ format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
+ // FIXME: unstable test case
+ EXPECT_EQ("L\"wide string \"\n"
+ "L\"literal\";",
+ format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
+ verifyFormat("@\"NSString \"\n"
+ "@\"literal\";",
+ "@\"NSString literal\";", getGoogleStyleWithColumns(19));
+ verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
+
+ // This input makes clang-format try to split the incomplete unicode escape
+ // sequence, which used to lead to a crasher.
+ verifyNoCrash(
+ "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ getLLVMStyleWithColumns(60));
+}
+
+TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
+ FormatStyle Style = getGoogleStyleWithColumns(15);
+ verifyFormat("R\"x(raw literal)x\";", Style);
+ verifyFormat("uR\"x(raw literal)x\";", Style);
+ verifyFormat("LR\"x(raw literal)x\";", Style);
+ verifyFormat("UR\"x(raw literal)x\";", Style);
+ verifyFormat("u8R\"x(raw literal)x\";", Style);
+}
+
+TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
+ FormatStyle Style = getLLVMStyleWithColumns(20);
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "_T(\"aaaaaaaaaaaaaa\")\n"
+ "_T(\"aaaaaaaaaaaaaa\")\n"
+ "_T(\"aaaaaaaaaaaa\")",
+ format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
+ verifyFormat("f(x,\n"
+ " _T(\"aaaaaaaaaaaa\")\n"
+ " _T(\"aaa\"),\n"
+ " z);",
+ "f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style);
+
+ // FIXME: Handle embedded spaces in one iteration.
+ // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
+ // "_T(\"aaaaaaaaaaaaa\")\n"
+ // "_T(\"aaaaaaaaaaaaa\")\n"
+ // "_T(\"a\")",
+ // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
+ // getLLVMStyleWithColumns(20)));
+ verifyFormat("_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
+ " _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style);
+ verifyFormat("f(\n"
+ "#if !TEST\n"
+ " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
+ "#endif\n"
+ ");",
+ "f(\n"
+ "#if !TEST\n"
+ "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
+ "#endif\n"
+ ");");
+ verifyFormat("f(\n"
+ "\n"
+ " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
+ "f(\n"
+ "\n"
+ "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));");
+ // Regression test for accessing tokens past the end of a vector in the
+ // TokenLexer.
+ verifyNoCrash(R"(_T(
+"
+)
+)");
+}
+
+TEST_F(FormatTest, BreaksStringLiteralOperands) {
+ // In a function call with two operands, the second can be broken with no line
+ // break before it.
+ verifyFormat("func(a, \"long long \"\n"
+ " \"long long\");",
+ "func(a, \"long long long long\");",
+ getLLVMStyleWithColumns(24));
+ // In a function call with three operands, the second must be broken with a
+ // line break before it.
+ verifyFormat("func(a,\n"
+ " \"long long long \"\n"
+ " \"long\",\n"
+ " c);",
+ "func(a, \"long long long long\", c);",
+ getLLVMStyleWithColumns(24));
+ // In a function call with three operands, the third must be broken with a
+ // line break before it.
+ verifyFormat("func(a, b,\n"
+ " \"long long long \"\n"
+ " \"long\");",
+ "func(a, b, \"long long long long\");",
+ getLLVMStyleWithColumns(24));
+ // In a function call with three operands, both the second and the third must
+ // be broken with a line break before them.
+ verifyFormat("func(a,\n"
+ " \"long long long \"\n"
+ " \"long\",\n"
+ " \"long long long \"\n"
+ " \"long\");",
+ "func(a, \"long long long long\", \"long long long long\");",
+ getLLVMStyleWithColumns(24));
+ // In a chain of << with two operands, the second can be broken with no line
+ // break before it.
+ verifyFormat("a << \"line line \"\n"
+ " \"line\";",
+ "a << \"line line line\";", getLLVMStyleWithColumns(20));
+ // In a chain of << with three operands, the second can be broken with no line
+ // break before it.
+ verifyFormat("abcde << \"line \"\n"
+ " \"line line\"\n"
+ " << c;",
+ "abcde << \"line line line\" << c;",
+ getLLVMStyleWithColumns(20));
+ // In a chain of << with three operands, the third must be broken with a line
+ // break before it.
+ verifyFormat("a << b\n"
+ " << \"line line \"\n"
+ " \"line\";",
+ "a << b << \"line line line\";", getLLVMStyleWithColumns(20));
+ // In a chain of << with three operands, the second can be broken with no line
+ // break before it and the third must be broken with a line break before it.
+ verifyFormat("abcd << \"line line \"\n"
+ " \"line\"\n"
+ " << \"line line \"\n"
+ " \"line\";",
+ "abcd << \"line line line\" << \"line line line\";",
+ getLLVMStyleWithColumns(20));
+ // In a chain of binary operators with two operands, the second can be broken
+ // with no line break before it.
+ verifyFormat("abcd + \"line line \"\n"
+ " \"line line\";",
+ "abcd + \"line line line line\";", getLLVMStyleWithColumns(20));
+ // In a chain of binary operators with three operands, the second must be
+ // broken with a line break before it.
+ verifyFormat("abcd +\n"
+ " \"line line \"\n"
+ " \"line line\" +\n"
+ " e;",
+ "abcd + \"line line line line\" + e;",
+ getLLVMStyleWithColumns(20));
+ // In a function call with two operands, with AlignAfterOpenBracket enabled,
+ // the first must be broken with a line break before it.
+ FormatStyle Style = getLLVMStyleWithColumns(25);
+ Style.BreakAfterOpenBracketFunction = true;
+ verifyFormat("someFunction(\n"
+ " \"long long long \"\n"
+ " \"long\",\n"
+ " a);",
+ "someFunction(\"long long long long\", a);", Style);
+ Style.BreakAfterOpenBracketFunction = true;
+ Style.BreakBeforeCloseBracketFunction = true;
+ verifyFormat("someFunction(\n"
+ " \"long long long \"\n"
+ " \"long\",\n"
+ " a\n"
+ ");",
+ Style);
+}
+
+TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
+ verifyFormat("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
+ "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";");
+}
+
+TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
+ verifyFormat("f(g(R\"x(raw literal)x\", a), b);",
+ "f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle());
+ verifyFormat("fffffffffff(g(R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\",\n"
+ " a),\n"
+ " b);",
+ "fffffffffff(g(R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\", a), b);",
+ getGoogleStyleWithColumns(20));
+ verifyFormat("fffffffffff(\n"
+ " g(R\"x(qqq\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\",\n"
+ " a),\n"
+ " b);",
+ "fffffffffff(g(R\"x(qqq\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\", a), b);",
+ getGoogleStyleWithColumns(20));
+
+ verifyNoChange("fffffffffff(R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\");",
+ getGoogleStyleWithColumns(20));
+ verifyFormat("fffffffffff(R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\" + bbbbbb);",
+ "fffffffffff(R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\" + bbbbbb);",
+ getGoogleStyleWithColumns(20));
+ verifyFormat("fffffffffff(\n"
+ " R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\" +\n"
+ " bbbbbb);",
+ "fffffffffff(\n"
+ " R\"x(\n"
+ "multiline raw string literal xxxxxxxxxxxxxx\n"
+ ")x\" + bbbbbb);",
+ getGoogleStyleWithColumns(20));
+ verifyFormat("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
+ "fffffffffff(\n"
+ " R\"(single line raw string)\" + bbbbbb);");
+}
+
+TEST_F(FormatTest, SkipsUnknownStringLiterals) {
+ verifyFormat("string a = \"unterminated;");
+ verifyFormat("function(\"unterminated,\n"
+ " OtherParameter);",
+ "function( \"unterminated,\n"
+ " OtherParameter);");
+}
+
+TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
+ FormatStyle Style = getLLVMStyle();
+ Style.Standard = FormatStyle::LS_Cpp03;
+ verifyFormat("#define x(_a) printf(\"foo\" _a);",
+ "#define x(_a) printf(\"foo\"_a);", Style);
+}
+
+TEST_F(FormatTest, CppLexVersion) {
+ FormatStyle Style = getLLVMStyle();
+ // Formatting of x * y differs if x is a type.
+ verifyFormat("void foo() { MACRO(a * b); }", Style);
+ verifyFormat("void foo() { MACRO(int *b); }", Style);
+
+ // LLVM style uses latest lexer.
+ verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
+ Style.Standard = FormatStyle::LS_Cpp17;
+ // But in c++17, char8_t isn't a keyword.
+ verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
+}
+
+TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
+
+TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
+ verifyFormat("someFunction(\"aaabbbcccd\"\n"
+ " \"ddeeefff\");",
+ "someFunction(\"aaabbbcccdddeeefff\");",
+ getLLVMStyleWithColumns(25));
+ verifyFormat("someFunction1234567890(\n"
+ " \"aaabbbcccdddeeefff\");",
+ "someFunction1234567890(\"aaabbbcccdddeeefff\");",
+ getLLVMStyleWithColumns(26));
+ verifyFormat("someFunction1234567890(\n"
+ " \"aaabbbcccdddeeeff\"\n"
+ " \"f\");",
+ "someFunction1234567890(\"aaabbbcccdddeeefff\");",
+ getLLVMStyleWithColumns(25));
+ verifyFormat("someFunction1234567890(\n"
+ " \"aaabbbcccdddeeeff\"\n"
+ " \"f\");",
+ "someFunction1234567890(\"aaabbbcccdddeeefff\");",
+ getLLVMStyleWithColumns(24));
+ verifyFormat("someFunction(\n"
+ " \"aaabbbcc ddde \"\n"
+ " \"efff\");",
+ "someFunction(\"aaabbbcc ddde efff\");",
+ getLLVMStyleWithColumns(25));
+ verifyFormat("someFunction(\"aaabbbccc \"\n"
+ " \"ddeeefff\");",
+ "someFunction(\"aaabbbccc ddeeefff\");",
+ getLLVMStyleWithColumns(25));
+ verifyFormat("someFunction1234567890(\n"
+ " \"aaabb \"\n"
+ " \"cccdddeeefff\");",
+ "someFunction1234567890(\"aaabb cccdddeeefff\");",
+ getLLVMStyleWithColumns(25));
+ verifyFormat("#define A \\\n"
+ " string s = \\\n"
+ " \"123456789\" \\\n"
+ " \"0\"; \\\n"
+ " int i;",
+ "#define A string s = \"1234567890\"; int i;",
+ getLLVMStyleWithColumns(20));
+ verifyFormat("someFunction(\n"
+ " \"aaabbbcc \"\n"
+ " \"dddeeefff\");",
+ "someFunction(\"aaabbbcc dddeeefff\");",
+ getLLVMStyleWithColumns(25));
+}
+
+TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
+ verifyFormat("\"\\a\"", getLLVMStyleWithColumns(3));
+ verifyFormat("\"\\\"", getLLVMStyleWithColumns(2));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"test\"\n"
+ "\"\\n\"",
+ format("\"test\\n\"", getLLVMStyleWithColumns(7)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"tes\\\\\"\n"
+ "\"n\"",
+ format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"\\\\\\\\\"\n"
+ "\"\\n\"",
+ format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
+ verifyFormat("\"\\uff01\"", getLLVMStyleWithColumns(7));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"\\uff01\"\n"
+ "\"test\"",
+ format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
+ verifyFormat("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"\\x000000000001\"\n"
+ "\"next\"",
+ format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
+ verifyFormat("\"\\x000000000001next\"", getLLVMStyleWithColumns(15));
+ verifyFormat("\"\\x000000000001\"", getLLVMStyleWithColumns(7));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"test\"\n"
+ "\"\\000000\"\n"
+ "\"000001\"",
+ format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"test\\000\"\n"
+ "\"00000000\"\n"
+ "\"1\"",
+ format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
+}
+
+TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
+ verifyFormat("void f() {\n"
+ " return g() {}\n"
+ " void h() {}");
+ verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
+ "g();\n"
+ "}");
+}
+
+TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
+ verifyFormat(
+ "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
+}
+
+TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
+ verifyFormat("class X {\n"
+ " void f() {\n"
+ " }\n"
+ "};",
+ getLLVMStyleWithColumns(12));
+}
+
+TEST_F(FormatTest, ConfigurableIndentWidth) {
+ FormatStyle EightIndent = getLLVMStyleWithColumns(18);
+ EightIndent.IndentWidth = 8;
+ EightIndent.ContinuationIndentWidth = 8;
+ verifyFormat("void f() {\n"
+ " someFunction();\n"
+ " if (true) {\n"
+ " f();\n"
+ " }\n"
+ "}",
+ EightIndent);
+ verifyFormat("class X {\n"
+ " void f() {\n"
+ " }\n"
+ "};",
+ EightIndent);
+ verifyFormat("int x[] = {\n"
+ " call(),\n"
+ " call()};",
+ EightIndent);
+}
+
+TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
+ verifyFormat("double\n"
+ "f();",
+ getLLVMStyleWithColumns(8));
+}
+
+TEST_F(FormatTest, ConfigurableUseOfTab) {
+ FormatStyle Tab = getLLVMStyleWithColumns(42);
+ Tab.IndentWidth = 8;
+ Tab.UseTab = FormatStyle::UT_Always;
+ Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb)\t\t// w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("if (aaa && bbb) // w\n"
+ "\t;",
+ "if(aaa&&bbb)// w\n"
+ ";",
+ Tab);
+
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("#define A \\\n"
+ "\tvoid f() { \\\n"
+ "\t\tsomeFunction( \\\n"
+ "\t\t parameter1, \\\n"
+ "\t\t parameter2); \\\n"
+ "\t}",
+ Tab);
+ verifyFormat("int a;\t // x\n"
+ "int bbbbbbbb; // x",
+ Tab);
+
+ FormatStyle TabAlignment = Tab;
+ TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("unsigned long long big;\n"
+ "char*\t\t ptr;",
+ TabAlignment);
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("unsigned long long big;\n"
+ "char *\t\t ptr;",
+ TabAlignment);
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+ verifyFormat("unsigned long long big;\n"
+ "char\t\t *ptr;",
+ TabAlignment);
+
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 8;
+ verifyFormat("class TabWidth4Indent8 {\n"
+ "\t\tvoid f() {\n"
+ "\t\t\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t\t\t parameter2);\n"
+ "\t\t}\n"
+ "};",
+ Tab);
+
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth4Indent4 {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth8Indent4 {\n"
+ " void f() {\n"
+ "\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ " }\n"
+ "};",
+ Tab);
+
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ verifyFormat("/*\n"
+ "\t a\t\tcomment\n"
+ "\t in multiple lines\n"
+ " */",
+ " /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab);
+
+ TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("void f() {\n"
+ "\tunsigned long long big;\n"
+ "\tchar* ptr;\n"
+ "}",
+ TabAlignment);
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("void f() {\n"
+ "\tunsigned long long big;\n"
+ "\tchar * ptr;\n"
+ "}",
+ TabAlignment);
+ TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+ verifyFormat("void f() {\n"
+ "\tunsigned long long big;\n"
+ "\tchar *ptr;\n"
+ "}",
+ TabAlignment);
+
+ Tab.UseTab = FormatStyle::UT_ForIndentation;
+ verifyFormat("{\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "};",
+ Tab);
+ verifyFormat("enum AA {\n"
+ "\ta1, // Force multiple lines\n"
+ "\ta2,\n"
+ "\ta3\n"
+ "};",
+ Tab);
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("{\n"
+ "\tQ(\n"
+ "\t {\n"
+ "\t\t int a;\n"
+ "\t\t someFunction(aaaaaaaa,\n"
+ "\t\t bbbbbbb);\n"
+ "\t },\n"
+ "\t p);\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ "{\n"
+ "/* aaaa\n"
+ " bbbb */\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "/*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t// bbbbbbbbbbbbb\n"
+ "}",
+ "{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ "\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ " asdf\n"
+ "\t*/\n"
+ "}",
+ Tab);
+
+ verifyFormat("void f() {\n"
+ "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
+ "\t : bbbbbbbbbbbbbbbbbb\n"
+ "}",
+ Tab);
+ FormatStyle TabNoBreak = Tab;
+ TabNoBreak.BreakBeforeTernaryOperators = false;
+ verifyFormat("void f() {\n"
+ "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
+ "\t bbbbbbbbbbbbbbbbbb\n"
+ "}",
+ TabNoBreak);
+ verifyFormat("void f() {\n"
+ "\treturn true ?\n"
+ "\t aaaaaaaaaaaaaaaaaaaa :\n"
+ "\t bbbbbbbbbbbbbbbbbbbb\n"
+ "}",
+ TabNoBreak);
+
+ Tab.UseTab = FormatStyle::UT_Never;
+ verifyFormat("/*\n"
+ " a\t\tcomment\n"
+ " in multiple lines\n"
+ " */",
+ " /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab);
+ verifyFormat("/* some\n"
+ " comment */",
+ " \t \t /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("int a; /* some\n"
+ " comment */",
+ " \t \t int a; /* some\n"
+ " \t \t comment */",
+ Tab);
+
+ verifyFormat("int a; /* some\n"
+ "comment */",
+ " \t \t int\ta; /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("f(\"\t\t\"); /* some\n"
+ " comment */",
+ " \t \t f(\"\t\t\"); /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("{\n"
+ " /*\n"
+ " * Comment\n"
+ " */\n"
+ " int i;\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\t int i;\n"
+ "}",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("if (aaa && bbb) // w\n"
+ "\t;",
+ "if(aaa&&bbb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("#define A \\\n"
+ "\tvoid f() { \\\n"
+ "\t\tsomeFunction( \\\n"
+ "\t\t parameter1, \\\n"
+ "\t\t parameter2); \\\n"
+ "\t}",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 8;
+ verifyFormat("class TabWidth4Indent8 {\n"
+ "\t\tvoid f() {\n"
+ "\t\t\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t\t\t parameter2);\n"
+ "\t\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth4Indent4 {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth8Indent4 {\n"
+ " void f() {\n"
+ "\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ " }\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ verifyFormat("/*\n"
+ "\t a\t\tcomment\n"
+ "\t in multiple lines\n"
+ " */",
+ " /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab);
+ verifyFormat("{\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "};",
+ Tab);
+ verifyFormat("enum AA {\n"
+ "\ta1, // Force multiple lines\n"
+ "\ta2,\n"
+ "\ta3\n"
+ "};",
+ Tab);
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("{\n"
+ "\tQ(\n"
+ "\t {\n"
+ "\t\t int a;\n"
+ "\t\t someFunction(aaaaaaaa,\n"
+ "\t\t\t\t bbbbbbb);\n"
+ "\t },\n"
+ "\t p);\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ "{\n"
+ "/* aaaa\n"
+ " bbbb */\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "/*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t// bbbbbbbbbbbbb\n"
+ "}",
+ "{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ "\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ " asdf\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyFormat("/* some\n"
+ " comment */",
+ " \t \t /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("int a; /* some\n"
+ " comment */",
+ " \t \t int a; /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("int a; /* some\n"
+ "comment */",
+ " \t \t int\ta; /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("f(\"\t\t\"); /* some\n"
+ " comment */",
+ " \t \t f(\"\t\t\"); /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\tint i;\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\t int i;\n"
+ "}",
+ Tab);
+ Tab.TabWidth = 2;
+ Tab.IndentWidth = 2;
+ verifyFormat("{\n"
+ "\t/* aaaa\n"
+ "\t\t bbbb */\n"
+ "}",
+ "{\n"
+ "/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t\tbbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "/*\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab);
+ Tab.AlignConsecutiveAssignments.Enabled = true;
+ Tab.AlignConsecutiveDeclarations.Enabled = true;
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class Assign {\n"
+ "\tvoid f() {\n"
+ "\t\tint x = 123;\n"
+ "\t\tint random = 4;\n"
+ "\t\tstd::string alphabet =\n"
+ "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
+ "\t}\n"
+ "};",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("if (aaa && bbb) // w\n"
+ "\t;",
+ "if(aaa&&bbb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("#define A \\\n"
+ "\tvoid f() { \\\n"
+ "\t\tsomeFunction( \\\n"
+ "\t\t parameter1, \\\n"
+ "\t\t parameter2); \\\n"
+ "\t}",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 8;
+ verifyFormat("class TabWidth4Indent8 {\n"
+ "\t\tvoid f() {\n"
+ "\t\t\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t parameter2);\n"
+ "\t\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth4Indent4 {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth8Indent4 {\n"
+ " void f() {\n"
+ "\tsomeFunction(parameter1,\n"
+ "\t parameter2);\n"
+ " }\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ verifyFormat("/*\n"
+ " a\t\tcomment\n"
+ " in multiple lines\n"
+ " */",
+ " /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab);
+ verifyFormat("{\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "};",
+ Tab);
+ verifyFormat("enum AA {\n"
+ "\ta1, // Force multiple lines\n"
+ "\ta2,\n"
+ "\ta3\n"
+ "};",
+ Tab);
+ verifyFormat("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ "if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab);
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("{\n"
+ "\tQ(\n"
+ "\t {\n"
+ "\t\t int a;\n"
+ "\t\t someFunction(aaaaaaaa,\n"
+ "\t\t bbbbbbb);\n"
+ "\t },\n"
+ "\t p);\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ "{\n"
+ "/* aaaa\n"
+ " bbbb */\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "/*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t// bbbbbbbbbbbbb\n"
+ "}",
+ "{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ "\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyNoChange("{\n"
+ "\t/*\n"
+ " asdf\n"
+ "\t*/\n"
+ "}",
+ Tab);
+ verifyFormat("/* some\n"
+ " comment */",
+ " \t \t /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("int a; /* some\n"
+ " comment */",
+ " \t \t int a; /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("int a; /* some\n"
+ "comment */",
+ " \t \t int\ta; /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("f(\"\t\t\"); /* some\n"
+ " comment */",
+ " \t \t f(\"\t\t\"); /* some\n"
+ " \t \t comment */",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\tint i;\n"
+ "}",
+ "{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\t int i;\n"
+ "}",
+ Tab);
+ Tab.TabWidth = 2;
+ Tab.IndentWidth = 2;
+ verifyFormat("{\n"
+ "\t/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ "{\n"
+ "/* aaaa\n"
+ " bbbb */\n"
+ "}",
+ Tab);
+ verifyFormat("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ "{\n"
+ "/*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab);
+ Tab.AlignConsecutiveAssignments.Enabled = true;
+ Tab.AlignConsecutiveDeclarations.Enabled = true;
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class Assign {\n"
+ "\tvoid f() {\n"
+ "\t\tint x = 123;\n"
+ "\t\tint random = 4;\n"
+ "\t\tstd::string alphabet =\n"
+ "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
+ "\t}\n"
+ "};",
+ Tab);
+ Tab.AlignOperands = FormatStyle::OAS_Align;
+ verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
+ " cccccccccccccccccccc;",
+ Tab);
+ // no alignment
+ verifyFormat("int aaaaaaaaaa =\n"
+ "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ Tab);
+ verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
+ " : bbbbbbbbbbbbbb ? 222222222222222\n"
+ " : 333333333333333;",
+ Tab);
+ Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
+ verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
+ " + cccccccccccccccccccc;",
+ Tab);
+
+ Tab.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Tab.BraceWrapping.BeforeLambdaBody = true;
+ verifyNoChange("example(\n"
+ "\t[]\n"
+ "\t{\n"
+ "\t\t// foo\n"
+ "\t\t// bar\n"
+ "\t});",
+ Tab);
+}
+
+TEST_F(FormatTest, ZeroTabWidth) {
+ FormatStyle Tab = getLLVMStyleWithColumns(42);
+ Tab.IndentWidth = 8;
+ Tab.UseTab = FormatStyle::UT_Never;
+ Tab.TabWidth = 0;
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_ForIndentation;
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ verifyFormat("void a() {\n"
+ " // line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ Tab.UseTab = FormatStyle::UT_Always;
+ verifyFormat("void a() {\n"
+ "// line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t// line starts with '\t'\n"
+ "};",
+ Tab);
+
+ verifyFormat("void a() {\n"
+ "// line starts with '\t'\n"
+ "};",
+ "void a(){\n"
+ "\t\t// line starts with '\t'\n"
+ "};",
+ Tab);
+}
+
+TEST_F(FormatTest, CalculatesOriginalColumn) {
+ verifyFormat("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "q\"; /* some\n"
+ " comment */",
+ " \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "q\"; /* some\n"
+ " comment */");
+ verifyFormat("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
+ "/* some\n"
+ " comment */",
+ "// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
+ " /* some\n"
+ " comment */");
+ verifyFormat("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "qqq\n"
+ "/* some\n"
+ " comment */",
+ "// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "qqq\n"
+ " /* some\n"
+ " comment */");
+ verifyFormat("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "wwww; /* some\n"
+ " comment */",
+ " inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
+ "wwww; /* some\n"
+ " comment */");
+}
+
+TEST_F(FormatTest, SpaceAfterOperatorKeyword) {
+ auto SpaceAfterOperatorKeyword = getLLVMStyle();
+ SpaceAfterOperatorKeyword.SpaceAfterOperatorKeyword = true;
+ verifyFormat("bool operator ++(int a);", SpaceAfterOperatorKeyword);
+}
+
+TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
+ FormatStyle NoSpace = getLLVMStyle();
+ NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
+
+ verifyFormat("while(true)\n"
+ " continue;",
+ NoSpace);
+ verifyFormat("for(;;)\n"
+ " continue;",
+ NoSpace);
+ verifyFormat("if(true)\n"
+ " f();\n"
+ "else if(true)\n"
+ " f();",
+ NoSpace);
+ verifyFormat("do {\n"
+ " do_something();\n"
+ "} while(something());",
+ NoSpace);
+ verifyFormat("switch(x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ NoSpace);
+ verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
+ verifyFormat("size_t x = sizeof(x);", NoSpace);
+ verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
+ verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
+ verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
+ verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
+ verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
+ verifyFormat("alignas(128) char a[128];", NoSpace);
+ verifyFormat("size_t x = alignof(MyType);", NoSpace);
+ verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
+ verifyFormat("int f() throw(Deprecated);", NoSpace);
+ verifyFormat("typedef void (*cb)(int);", NoSpace);
+ verifyFormat("T A::operator()();", NoSpace);
+ verifyFormat("X A::operator++(T);", NoSpace);
+ verifyFormat("auto lambda = []() { return 0; };", NoSpace);
+ verifyFormat("#if (foo || bar) && baz\n"
+ "#elif ((a || b) && c) || d\n"
+ "#endif",
+ NoSpace);
+ // Space between sizeof and C compound literal.
+ verifyFormat("a = sizeof (int){};", NoSpace);
+
+ FormatStyle Space = getLLVMStyle();
+ Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
+
+ verifyFormat("int f ();", Space);
+ verifyFormat("bool operator< ();", Space);
+ verifyFormat("bool operator> ();", Space);
+ verifyFormat("void f (int a, T b) {\n"
+ " while (true)\n"
+ " continue;\n"
+ "}",
+ Space);
+ verifyFormat("if (true)\n"
+ " f ();\n"
+ "else if (true)\n"
+ " f ();",
+ Space);
+ verifyFormat("do {\n"
+ " do_something ();\n"
+ "} while (something ());",
+ Space);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Space);
+ verifyFormat("A::A () : a (1) {}", Space);
+ verifyFormat("void f () __attribute__ ((asdf));", Space);
+ verifyFormat("*(&a + 1);\n"
+ "&((&a)[1]);\n"
+ "a[(b + c) * d];\n"
+ "(((a + 1) * 2) + 3) * 4;",
+ Space);
+ verifyFormat("#define A(x) x", Space);
+ verifyFormat("#define A (x) x", Space);
+ verifyFormat("#if defined(x)\n"
+ "#endif",
+ Space);
+ verifyFormat("auto i = std::make_unique<int> (5);", Space);
+ verifyFormat("size_t x = sizeof (x);", Space);
+ verifyFormat("auto f (int x) -> decltype (x);", Space);
+ verifyFormat("auto f (int x) -> typeof (x);", Space);
+ verifyFormat("auto f (int x) -> _Atomic (x);", Space);
+ verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
+ verifyFormat("int f (T x) noexcept (x.create ());", Space);
+ verifyFormat("alignas (128) char a[128];", Space);
+ verifyFormat("size_t x = alignof (MyType);", Space);
+ verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
+ verifyFormat("int f () throw (Deprecated);", Space);
+ verifyFormat("typedef void (*cb) (int);", Space);
+ verifyFormat("T A::operator() ();", Space);
+ verifyFormat("X A::operator++ (T);", Space);
+ verifyFormat("auto lambda = [] () { return 0; };", Space);
+ verifyFormat("int x = int (y);", Space);
+ verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
+ verifyFormat("__builtin_LINE ()", Space);
+ verifyFormat("__builtin_UNKNOWN ()", Space);
+
+ FormatStyle SomeSpace = getLLVMStyle();
+ SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
+
+ verifyFormat("[]() -> float {}", SomeSpace);
+ verifyFormat("[] (auto foo) {}", SomeSpace);
+ verifyFormat("[foo]() -> int {}", SomeSpace);
+ verifyFormat("int f();", SomeSpace);
+ verifyFormat("void f (int a, T b) {\n"
+ " while (true)\n"
+ " continue;\n"
+ "}",
+ SomeSpace);
+ verifyFormat("if (true)\n"
+ " f();\n"
+ "else if (true)\n"
+ " f();",
+ SomeSpace);
+ verifyFormat("do {\n"
+ " do_something();\n"
+ "} while (something());",
+ SomeSpace);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ SomeSpace);
+ verifyFormat("A::A() : a (1) {}", SomeSpace);
+ verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
+ verifyFormat("*(&a + 1);\n"
+ "&((&a)[1]);\n"
+ "a[(b + c) * d];\n"
+ "(((a + 1) * 2) + 3) * 4;",
+ SomeSpace);
+ verifyFormat("#define A(x) x", SomeSpace);
+ verifyFormat("#define A (x) x", SomeSpace);
+ verifyFormat("#if defined(x)\n"
+ "#endif",
+ SomeSpace);
+ verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
+ verifyFormat("size_t x = sizeof (x);", SomeSpace);
+ verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
+ verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
+ verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
+ verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
+ verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
+ verifyFormat("alignas (128) char a[128];", SomeSpace);
+ verifyFormat("size_t x = alignof (MyType);", SomeSpace);
+ verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
+ SomeSpace);
+ verifyFormat("int f() throw (Deprecated);", SomeSpace);
+ verifyFormat("typedef void (*cb) (int);", SomeSpace);
+ verifyFormat("T A::operator()();", SomeSpace);
+ verifyFormat("X A::operator++ (T);", SomeSpace);
+ verifyFormat("int x = int (y);", SomeSpace);
+ verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
+
+ FormatStyle SpaceControlStatements = getLLVMStyle();
+ SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
+
+ verifyFormat("while (true)\n"
+ " continue;",
+ SpaceControlStatements);
+ verifyFormat("if (true)\n"
+ " f();\n"
+ "else if (true)\n"
+ " f();",
+ SpaceControlStatements);
+ verifyFormat("for (;;) {\n"
+ " do_something();\n"
+ "}",
+ SpaceControlStatements);
+ verifyFormat("do {\n"
+ " do_something();\n"
+ "} while (something());",
+ SpaceControlStatements);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ SpaceControlStatements);
+
+ FormatStyle SpaceFuncDecl = getLLVMStyle();
+ SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
+
+ verifyFormat("int f ();", SpaceFuncDecl);
+ verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
+ verifyFormat("void __attribute__((asdf)) f(int a, T b) {}", SpaceFuncDecl);
+ verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
+ verifyFormat("template <> void A<C> (C x);", SpaceFuncDecl);
+ verifyFormat("template <> void A<C>(C x) {}", SpaceFuncDecl);
+ verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
+ verifyFormat("void __attribute__((asdf)) f ();", SpaceFuncDecl);
+ verifyFormat("#define A(x) x", SpaceFuncDecl);
+ verifyFormat("#define A (x) x", SpaceFuncDecl);
+ verifyFormat("#if defined(x)\n"
+ "#endif",
+ SpaceFuncDecl);
+ verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
+ verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
+ verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
+ verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
+ verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
+ verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
+ verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
+ verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
+ verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
+ verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
+ SpaceFuncDecl);
+ verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
+ verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
+ verifyFormat("T A::operator()();", SpaceFuncDecl);
+ verifyFormat("X A::operator++(T);", SpaceFuncDecl);
+ verifyFormat("T A::operator()() {}", SpaceFuncDecl);
+ verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
+ verifyFormat("int x = int(y);", SpaceFuncDecl);
+ verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
+ SpaceFuncDecl);
+
+ FormatStyle SpaceFuncDef = getLLVMStyle();
+ SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
+
+ verifyFormat("int f();", SpaceFuncDef);
+ verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
+ verifyFormat("void __attribute__((asdf)) f (int a, T b) {}", SpaceFuncDef);
+ verifyFormat("A::A () : a(1) {}", SpaceFuncDef);
+ verifyFormat("template <> void A<C>(C x);", SpaceFuncDef);
+ verifyFormat("template <> void A<C> (C x) {}", SpaceFuncDef);
+ verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
+ verifyFormat("void __attribute__((asdf)) f();", SpaceFuncDef);
+ verifyFormat("#define A(x) x", SpaceFuncDef);
+ verifyFormat("#define A (x) x", SpaceFuncDef);
+ verifyFormat("#if defined(x)\n"
+ "#endif",
+ SpaceFuncDef);
+ verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
+ verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
+ verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
+ verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
+ verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
+ verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
+ verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
+ verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
+ verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
+ verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
+ SpaceFuncDef);
+ verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
+ verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
+ verifyFormat("T A::operator()();", SpaceFuncDef);
+ verifyFormat("X A::operator++(T);", SpaceFuncDef);
+ verifyFormat("T A::operator()() {}", SpaceFuncDef);
+ verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
+ verifyFormat("int x = int(y);", SpaceFuncDef);
+ verifyFormat("void foo::bar () {}", SpaceFuncDef);
+ verifyFormat("M (std::size_t R, std::size_t C) : C(C), data(R) {}",
+ SpaceFuncDef);
+
+ FormatStyle SpaceIfMacros = getLLVMStyle();
+ SpaceIfMacros.IfMacros.clear();
+ SpaceIfMacros.IfMacros.push_back("MYIF");
+ SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
+ verifyFormat("MYIF (a)\n return;", SpaceIfMacros);
+ verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros);
+ verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros);
+
+ FormatStyle SpaceForeachMacros = getLLVMStyle();
+ EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
+ FormatStyle::SBS_Never);
+ EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
+ SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
+ verifyFormat("for (;;) {\n"
+ "}",
+ SpaceForeachMacros);
+ verifyFormat("foreach (Item *item, itemlist) {\n"
+ "}",
+ SpaceForeachMacros);
+ verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
+ "}",
+ SpaceForeachMacros);
+ verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
+ "}",
+ SpaceForeachMacros);
+ verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
+
+ FormatStyle SomeSpace2 = getLLVMStyle();
+ SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
+ verifyFormat("[]() -> float {}", SomeSpace2);
+ verifyFormat("[] (auto foo) {}", SomeSpace2);
+ verifyFormat("[foo]() -> int {}", SomeSpace2);
+ verifyFormat("int f();", SomeSpace2);
+ verifyFormat("void f (int a, T b) {\n"
+ " while (true)\n"
+ " continue;\n"
+ "}",
+ SomeSpace2);
+ verifyFormat("if (true)\n"
+ " f();\n"
+ "else if (true)\n"
+ " f();",
+ SomeSpace2);
+ verifyFormat("do {\n"
+ " do_something();\n"
+ "} while (something());",
+ SomeSpace2);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ SomeSpace2);
+ verifyFormat("A::A() : a (1) {}", SomeSpace2);
+ verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
+ verifyFormat("*(&a + 1);\n"
+ "&((&a)[1]);\n"
+ "a[(b + c) * d];\n"
+ "(((a + 1) * 2) + 3) * 4;",
+ SomeSpace2);
+ verifyFormat("#define A(x) x", SomeSpace2);
+ verifyFormat("#define A (x) x", SomeSpace2);
+ verifyFormat("#if defined(x)\n"
+ "#endif",
+ SomeSpace2);
+ verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
+ verifyFormat("size_t x = sizeof (x);", SomeSpace2);
+ verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
+ verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
+ verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
+ verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
+ verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
+ verifyFormat("alignas (128) char a[128];", SomeSpace2);
+ verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
+ verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
+ SomeSpace2);
+ verifyFormat("int f() throw (Deprecated);", SomeSpace2);
+ verifyFormat("typedef void (*cb) (int);", SomeSpace2);
+ verifyFormat("T A::operator()();", SomeSpace2);
+ verifyFormat("X A::operator++ (T);", SomeSpace2);
+ verifyFormat("int x = int (y);", SomeSpace2);
+ verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
+
+ auto Style = getLLVMStyle();
+ Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ EXPECT_FALSE(Style.SpaceBeforeParensOptions.AfterNot);
+ Style.SpaceBeforeParensOptions.AfterNot = true;
+ verifyFormat("return not (a || b);", Style);
+
+ FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
+ SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
+ .AfterOverloadedOperator = true;
+
+ verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
+ verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
+ verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
+ verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
+
+ SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
+ .AfterOverloadedOperator = false;
+
+ verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
+ verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
+ verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
+ verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
+
+ auto SpaceAfterRequires = getLLVMStyle();
+ SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+ EXPECT_FALSE(
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
+ EXPECT_FALSE(
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
+ verifyFormat("void f(auto x)\n"
+ " requires requires(int i) { x + i; }\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("void f(auto x)\n"
+ " requires(requires(int i) { x + i; })\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("if (requires(int i) { x + i; })\n"
+ " return;",
+ SpaceAfterRequires);
+ verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T>)\n"
+ "class Bar;",
+ SpaceAfterRequires);
+
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
+ verifyFormat("void f(auto x)\n"
+ " requires requires(int i) { x + i; }\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("void f(auto x)\n"
+ " requires (requires(int i) { x + i; })\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("if (requires(int i) { x + i; })\n"
+ " return;",
+ SpaceAfterRequires);
+ verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
+ verifyFormat("template <typename T>\n"
+ " requires (Foo<T>)\n"
+ "class Bar;",
+ SpaceAfterRequires);
+
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
+ verifyFormat("void f(auto x)\n"
+ " requires requires (int i) { x + i; }\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("void f(auto x)\n"
+ " requires(requires (int i) { x + i; })\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("if (requires (int i) { x + i; })\n"
+ " return;",
+ SpaceAfterRequires);
+ verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T>)\n"
+ "class Bar;",
+ SpaceAfterRequires);
+
+ SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
+ verifyFormat("void f(auto x)\n"
+ " requires requires (int i) { x + i; }\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("void f(auto x)\n"
+ " requires (requires (int i) { x + i; })\n"
+ "{}",
+ SpaceAfterRequires);
+ verifyFormat("if (requires (int i) { x + i; })\n"
+ " return;",
+ SpaceAfterRequires);
+ verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
+ verifyFormat("template <typename T>\n"
+ " requires (Foo<T>)\n"
+ "class Bar;",
+ SpaceAfterRequires);
+}
+
+TEST_F(FormatTest, SpaceAfterLogicalNot) {
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpaceAfterLogicalNot = true;
+
+ verifyFormat("bool x = ! y", Spaces);
+ verifyFormat("if (! isFailure())", Spaces);
+ verifyFormat("if (! (a && b))", Spaces);
+ verifyFormat("\"Error!\"", Spaces);
+ verifyFormat("! ! x", Spaces);
+}
+
+TEST_F(FormatTest, ConfigurableSpacesInParens) {
+ FormatStyle Spaces = getLLVMStyle();
+
+ verifyFormat("do_something(::globalVar);", Spaces);
+ verifyFormat("call(x, y, z);", Spaces);
+ verifyFormat("call();", Spaces);
+ verifyFormat("std::function<void(int, int)> callback;", Spaces);
+ verifyFormat("void inFunction() { std::function<void(int, int)> fct; }",
+ Spaces);
+ verifyFormat("while ((bool)1)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("for (;;)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("if (true)\n"
+ " f();\n"
+ "else if (true)\n"
+ " f();",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something((int)i);\n"
+ "} while (something());",
+ Spaces);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+ verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
+ verifyFormat("void f() __attribute__((asdf));", Spaces);
+ verifyFormat("x = (int32)y;", Spaces);
+ verifyFormat("y = ((int (*)(int))foo)(x);", Spaces);
+ verifyFormat("decltype(x) y = 42;", Spaces);
+ verifyFormat("decltype((x)) y = z;", Spaces);
+ verifyFormat("decltype((foo())) a = foo();", Spaces);
+ verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
+ verifyFormat("if ((x - y) && (a ^ b))\n"
+ " f();",
+ Spaces);
+ verifyFormat("for (int i = 0; i < 10; i = (i + 1))\n"
+ " foo(i);",
+ Spaces);
+ verifyFormat("switch (x / (y + z)) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.Other = true;
+
+ EXPECT_FALSE(Spaces.SpacesInParensOptions.InConditionalStatements);
+ verifyFormat("if (a)\n"
+ " return;",
+ Spaces);
+
+ Spaces.SpacesInParensOptions.InConditionalStatements = true;
+ verifyFormat("do_something( ::globalVar );", Spaces);
+ verifyFormat("call( x, y, z );", Spaces);
+ verifyFormat("call();", Spaces);
+ verifyFormat("std::function<void( int, int )> callback;", Spaces);
+ verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
+ Spaces);
+ verifyFormat("while ( (bool)1 )\n"
+ " continue;",
+ Spaces);
+ verifyFormat("for ( ;; )\n"
+ " continue;",
+ Spaces);
+ verifyFormat("if ( true )\n"
+ " f();\n"
+ "else if ( true )\n"
+ " f();",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something( (int)i );\n"
+ "} while ( something() );",
+ Spaces);
+ verifyFormat("switch ( x ) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+ verifyFormat("SomeType *__attribute__( ( attr ) ) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__( ( naked ) ) foo( int bar )", Spaces);
+ verifyFormat("void f() __attribute__( ( asdf ) );", Spaces);
+ verifyFormat("x = (int32)y;", Spaces);
+ verifyFormat("y = ( (int ( * )( int ))foo )( x );", Spaces);
+ verifyFormat("decltype( x ) y = 42;", Spaces);
+ verifyFormat("decltype( ( x ) ) y = z;", Spaces);
+ verifyFormat("decltype( ( foo() ) ) a = foo();", Spaces);
+ verifyFormat("decltype( ( bar( 10 ) ) ) a = bar( 11 );", Spaces);
+ verifyFormat("if ( ( x - y ) && ( a ^ b ) )\n"
+ " f();",
+ Spaces);
+ verifyFormat("for ( int i = 0; i < 10; i = ( i + 1 ) )\n"
+ " foo( i );",
+ Spaces);
+ verifyFormat("switch ( x / ( y + z ) ) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.InCStyleCasts = true;
+ verifyFormat("Type *A = ( Type * )P;", Spaces);
+ verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
+ verifyFormat("x = ( int32 )y;", Spaces);
+ verifyFormat("throw ( int32 )x;", Spaces);
+ verifyFormat("int a = ( int )(2.0f);", Spaces);
+ verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
+ verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
+ verifyFormat("#define x (( int )-1)", Spaces);
+ verifyFormat("y = (( int (*)(int) )foo)(x);", Spaces);
+
+ // Run the first set of tests again with:
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.InEmptyParentheses = true;
+ Spaces.SpacesInParensOptions.InCStyleCasts = true;
+ verifyFormat("call(x, y, z);", Spaces);
+ verifyFormat("call( );", Spaces);
+ verifyFormat("std::function<void(int, int)> callback;", Spaces);
+ verifyFormat("while (( bool )1)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("for (;;)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("if (true)\n"
+ " f( );\n"
+ "else if (true)\n"
+ " f( );",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something(( int )i);\n"
+ "} while (something( ));",
+ Spaces);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+ verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
+ verifyFormat("void f( ) __attribute__((asdf));", Spaces);
+ verifyFormat("x = ( int32 )y;", Spaces);
+ verifyFormat("y = (( int (*)(int) )foo)(x);", Spaces);
+ verifyFormat("decltype(x) y = 42;", Spaces);
+ verifyFormat("decltype((x)) y = z;", Spaces);
+ verifyFormat("decltype((foo( ))) a = foo( );", Spaces);
+ verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
+ verifyFormat("if ((x - y) && (a ^ b))\n"
+ " f( );",
+ Spaces);
+ verifyFormat("for (int i = 0; i < 10; i = (i + 1))\n"
+ " foo(i);",
+ Spaces);
+ verifyFormat("switch (x / (y + z)) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+
+ // Run the first set of tests again with:
+ Spaces.SpaceAfterCStyleCast = true;
+ verifyFormat("call(x, y, z);", Spaces);
+ verifyFormat("call( );", Spaces);
+ verifyFormat("std::function<void(int, int)> callback;", Spaces);
+ verifyFormat("while (( bool ) 1)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("for (;;)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("if (true)\n"
+ " f( );\n"
+ "else if (true)\n"
+ " f( );",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something(( int ) i);\n"
+ "} while (something( ));",
+ Spaces);
+ verifyFormat("switch (x) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+ verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
+ verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
+ verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
+ verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
+ verifyFormat("bool *y = ( bool * ) (x);", Spaces);
+ verifyFormat("throw ( int32 ) x;", Spaces);
+ verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
+ verifyFormat("void f( ) __attribute__((asdf));", Spaces);
+
+ // Run subset of tests again with:
+ Spaces.SpacesInParensOptions.InCStyleCasts = false;
+ Spaces.SpaceAfterCStyleCast = true;
+ verifyFormat("while ((bool) 1)\n"
+ " continue;",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something((int) i);\n"
+ "} while (something( ));",
+ Spaces);
+
+ verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
+ verifyFormat("size_t idx = (size_t) a;", Spaces);
+ verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
+ verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
+ verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
+ verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
+ verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
+ verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
+ verifyFormat("throw (int32) x;", Spaces);
+ verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
+ verifyFormat("void f( ) __attribute__((asdf));", Spaces);
+
+ Spaces.ColumnLimit = 80;
+ Spaces.IndentWidth = 4;
+ Spaces.BreakAfterOpenBracketFunction = true;
+ verifyFormat("void foo( ) {\n"
+ " size_t foo = (*(function))(\n"
+ " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
+ "BarrrrrrrrrrrrLong,\n"
+ " FoooooooooLooooong);\n"
+ "}",
+ Spaces);
+ Spaces.SpaceAfterCStyleCast = false;
+ verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
+ verifyFormat("size_t idx = (size_t)a;", Spaces);
+ verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
+
+ verifyFormat("void foo( ) {\n"
+ " size_t foo = (*(function))(\n"
+ " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
+ "BarrrrrrrrrrrrLong,\n"
+ " FoooooooooLooooong);\n"
+ "}",
+ Spaces);
+
+ Spaces.BreakAfterOpenBracketFunction = true;
+ Spaces.BreakBeforeCloseBracketFunction = true;
+ verifyFormat("void foo( ) {\n"
+ " size_t foo = (*(function))(\n"
+ " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
+ "BarrrrrrrrrrrrLong,\n"
+ " FoooooooooLooooong\n"
+ " );\n"
+ "}",
+ Spaces);
+ verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
+ verifyFormat("size_t idx = (size_t)a;", Spaces);
+ verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
+ verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
+
+ // Check ExceptDoubleParentheses spaces
+ Spaces.IndentWidth = 2;
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.Other = true;
+ Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
+ verifyFormat("SomeType *__attribute__(( attr )) *a = NULL;", Spaces);
+ verifyFormat("void __attribute__(( naked )) foo( int bar )", Spaces);
+ verifyFormat("void f() __attribute__(( asdf ));", Spaces);
+ verifyFormat("__attribute__(( __aligned__( x ) )) z;", Spaces);
+ verifyFormat("int x __attribute__(( aligned( 16 ) )) = 0;", Spaces);
+ verifyFormat("class __declspec( dllimport ) X {};", Spaces);
+ verifyFormat("class __declspec(( dllimport )) X {};", Spaces);
+ verifyFormat("int x = ( ( a - 1 ) * 3 );", Spaces);
+ verifyFormat("int x = ( 3 * ( a - 1 ) );", Spaces);
+ verifyFormat("decltype( x ) y = 42;", Spaces);
+ verifyFormat("decltype(( bar( 10 ) )) a = bar( 11 );", Spaces);
+ verifyFormat("if (( i = j ))\n"
+ " do_something( i );",
+ Spaces);
+
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions = {};
+ Spaces.SpacesInParensOptions.InConditionalStatements = true;
+ Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
+ verifyFormat("while ( (bool)1 )\n"
+ " continue;",
+ Spaces);
+ verifyFormat("while ((i = j))\n"
+ " continue;",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something((int)i);\n"
+ "} while ( something() );",
+ Spaces);
+ verifyFormat("do {\n"
+ " do_something((int)i);\n"
+ "} while ((i = i + 1));",
+ Spaces);
+ verifyFormat("if ( (x - y) && (a ^ b) )\n"
+ " f();",
+ Spaces);
+ verifyFormat("if ((i = j))\n"
+ " do_something(i);",
+ Spaces);
+ verifyFormat("for ( int i = 0; i < 10; i = (i + 1) )\n"
+ " foo(i);",
+ Spaces);
+ verifyFormat("switch ( x / (y + z) ) {\n"
+ "default:\n"
+ " break;\n"
+ "}",
+ Spaces);
+ verifyFormat("if constexpr ((a = b))\n"
+ " c;",
+ Spaces);
+}
+
+TEST_F(FormatTest, SpaceAfterCompoundLiteralType) {
+ FormatStyle Style = getLLVMStyle();
+
+ // --- Feature enabled ---
+ Style.SpaceAfterCompoundLiteralType = true;
+
+ // Basic primitive type
+ verifyFormat("int i = (int) {1, 2, 3};", Style);
+
+ // Struct type
+ verifyFormat("f((struct foo) {1, 2, 3});", Style);
+
+ // Pointer type
+ verifyFormat("void *p = (void *) {0};", Style);
+
+ // Nested compound literal
+ verifyFormat("int i = (int) {(int) {1}};", Style);
+
+ // Assignment to struct
+ verifyFormat("struct point p = (struct point) {1, 2};", Style);
+
+ // Used as function argument
+ verifyFormat("foo((int) {1, 2, 3});", Style);
+
+ // Multiple arguments, one is compound literal
+ verifyFormat("foo(x, (int) {1, 2, 3}, y);", Style);
+
+ // Empty braces
+ verifyFormat("int i = (int) {};", Style);
+
+ // Multi-line / designated initializers
+ verifyFormat("struct foo s = (struct foo) {.x = 1, .y = 2};", Style);
+
+ // Typedef'd type
+ verifyFormat("MyType t = (MyType) {1, 2, 3};", Style);
+
+ // --- Feature disabled (default behavior) ---
+ Style.SpaceAfterCompoundLiteralType = false;
+
+ // Basic primitive type
+ verifyFormat("int i = (int){1, 2, 3};", Style);
+
+ // Struct type
+ verifyFormat("f((struct foo){1, 2, 3});", Style);
+
+ // Pointer type
+ verifyFormat("void *p = (void *){0};", Style);
+
+ // Nested compound literal
+ verifyFormat("int i = (int){(int){1}};", Style);
+
+ // Assignment to struct
+ verifyFormat("struct point p = (struct point){1, 2};", Style);
+
+ // Used as function argument
+ verifyFormat("foo((int){1, 2, 3});", Style);
+
+ // Multiple arguments, one is compound literal
+ verifyFormat("foo(x, (int){1, 2, 3}, y);", Style);
+
+ // Empty braces
+ verifyFormat("int i = (int){};", Style);
+
+ // Multi-line / designated initializers
+ verifyFormat("struct foo s = (struct foo){.x = 1, .y = 2};", Style);
+
+ // Typedef'd type
+ verifyFormat("MyType t = (MyType){1, 2, 3};", Style);
+
+ // --- Interaction: SpaceAfterCompoundLiteralType=true should NOT
+ // affect regular C-style casts (no brace follows) ---
+ Style.SpaceAfterCompoundLiteralType = true;
+ Style.SpaceAfterCStyleCast = false;
+
+ // Regular cast — no space, unaffected by our option
+ verifyFormat("int x = (int)y;", Style);
+ verifyFormat("int x = (int)(y + z);", Style);
+ verifyFormat("void *p = (void *)ptr;", Style);
+
+ // --- Interaction: both options enabled ---
+ Style.SpaceAfterCompoundLiteralType = true;
+ Style.SpaceAfterCStyleCast = true;
+
+ // Regular cast gets space from SpaceAfterCStyleCast
+ verifyFormat("int x = (int) y;", Style);
+
+ // Compound literal also gets space from SpaceAfterCompoundLiteralType
+ verifyFormat("int i = (int) {1, 2, 3};", Style);
+}
+
+TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
+ verifyFormat("int a[5];");
+ verifyFormat("a[3] += 42;");
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInSquareBrackets = true;
+ // Not lambdas.
+ verifyFormat("int a[ 5 ];", Spaces);
+ verifyFormat("a[ 3 ] += 42;", Spaces);
+ verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
+ verifyFormat("double &operator[](int i) { return 0; }\n"
+ "int i;",
+ Spaces);
+ verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
+ verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
+ verifyFormat("int i = (*b)[ a ]->f();", Spaces);
+ // Lambdas.
+ verifyFormat("int c = []() -> int { return 2; }();", Spaces);
+ verifyFormat("return [ i, args... ] {};", Spaces);
+ verifyFormat("int foo = [ &bar ]() {};", Spaces);
+ verifyFormat("int foo = [ = ]() {};", Spaces);
+ verifyFormat("int foo = [ & ]() {};", Spaces);
+ verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
+ verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
+}
+
+TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
+ FormatStyle NoSpaceStyle = getLLVMStyle();
+ verifyFormat("int a[5];", NoSpaceStyle);
+ verifyFormat("a[3] += 42;", NoSpaceStyle);
+
+ verifyFormat("int a[1];", NoSpaceStyle);
+ verifyFormat("int 1 [a];", NoSpaceStyle);
+ verifyFormat("int a[1][2];", NoSpaceStyle);
+ verifyFormat("a[7] = 5;", NoSpaceStyle);
+ verifyFormat("int a = (f())[23];", NoSpaceStyle);
+ verifyFormat("f([] {})", NoSpaceStyle);
+
+ FormatStyle Space = getLLVMStyle();
+ Space.SpaceBeforeSquareBrackets = true;
+ verifyFormat("int c = []() -> int { return 2; }();", Space);
+ verifyFormat("return [i, args...] {};", Space);
+
+ verifyFormat("int a [5];", Space);
+ verifyFormat("a [3] += 42;", Space);
+ verifyFormat("constexpr char hello []{\"hello\"};", Space);
+ verifyFormat("double &operator[](int i) { return 0; }\n"
+ "int i;",
+ Space);
+ verifyFormat("std::unique_ptr<int []> foo() {}", Space);
+ verifyFormat("int i = a [a][a]->f();", Space);
+ verifyFormat("int i = (*b) [a]->f();", Space);
+
+ verifyFormat("int a [1];", Space);
+ verifyFormat("int 1 [a];", Space);
+ verifyFormat("int a [1][2];", Space);
+ verifyFormat("a [7] = 5;", Space);
+ verifyFormat("int a = (f()) [23];", Space);
+ verifyFormat("f([] {})", Space);
+}
+
+TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
+ verifyFormat("int a = 5;");
+ verifyFormat("a += 42;");
+ verifyFormat("a or_eq 8;");
+
+ auto Spaces = getLLVMStyle(FormatStyle::LK_C);
+ verifyFormat("xor = foo;", Spaces);
+
+ Spaces.Language = FormatStyle::LK_Cpp;
+ Spaces.SpaceBeforeAssignmentOperators = false;
+ verifyFormat("int a= 5;", Spaces);
+ verifyFormat("a+= 42;", Spaces);
+ verifyFormat("a or_eq 8;", Spaces);
+ verifyFormat("xor= foo;", Spaces);
+}
+
+TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
+ verifyFormat("class Foo : public Bar {};");
+ verifyFormat("Foo::Foo() : foo(1) {}");
+ verifyFormat("for (auto a : b) {\n}");
+ verifyFormat("int x = a ? b : c;");
+ verifyFormat("{\n"
+ "label0:\n"
+ " int x = 0;\n"
+ "}");
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ "default:\n"
+ "}");
+ verifyFormat("switch (allBraces) {\n"
+ "case 1: {\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default: {\n"
+ " break;\n"
+ "}\n"
+ "}");
+
+ FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
+ CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
+ verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
+ verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
+ verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
+ verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
+ verifyFormat("{\n"
+ "label1:\n"
+ " int x = 0;\n"
+ "}",
+ CtorInitializerStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ "default:\n"
+ "}",
+ CtorInitializerStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1: {\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default: {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ CtorInitializerStyle);
+ CtorInitializerStyle.BreakConstructorInitializers =
+ FormatStyle::BCIS_AfterColon;
+ verifyFormat("Fooooooooooo::Fooooooooooo():\n"
+ " aaaaaaaaaaaaaaaa(1),\n"
+ " bbbbbbbbbbbbbbbb(2) {}",
+ CtorInitializerStyle);
+ CtorInitializerStyle.BreakConstructorInitializers =
+ FormatStyle::BCIS_BeforeComma;
+ verifyFormat("Fooooooooooo::Fooooooooooo()\n"
+ " : aaaaaaaaaaaaaaaa(1)\n"
+ " , bbbbbbbbbbbbbbbb(2) {}",
+ CtorInitializerStyle);
+ CtorInitializerStyle.BreakConstructorInitializers =
+ FormatStyle::BCIS_BeforeColon;
+ verifyFormat("Fooooooooooo::Fooooooooooo()\n"
+ " : aaaaaaaaaaaaaaaa(1),\n"
+ " bbbbbbbbbbbbbbbb(2) {}",
+ CtorInitializerStyle);
+ CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
+ verifyFormat("Fooooooooooo::Fooooooooooo()\n"
+ ": aaaaaaaaaaaaaaaa(1),\n"
+ " bbbbbbbbbbbbbbbb(2) {}",
+ CtorInitializerStyle);
+
+ FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
+ InheritanceStyle.SpaceBeforeInheritanceColon = false;
+ verifyFormat("class Foo: public Bar {};", InheritanceStyle);
+ verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
+ verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
+ verifyFormat("int x = a ? b : c;", InheritanceStyle);
+ verifyFormat("{\n"
+ "label2:\n"
+ " int x = 0;\n"
+ "}",
+ InheritanceStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ "default:\n"
+ "}",
+ InheritanceStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1: {\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default: {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ InheritanceStyle);
+ InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
+ verifyFormat("class Foooooooooooooooooooooo\n"
+ " : public aaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbb {\n"
+ "}",
+ InheritanceStyle);
+ InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
+ verifyFormat("class Foooooooooooooooooooooo:\n"
+ " public aaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbb {\n"
+ "}",
+ InheritanceStyle);
+ InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+ verifyFormat("class Foooooooooooooooooooooo\n"
+ " : public aaaaaaaaaaaaaaaaaa\n"
+ " , public bbbbbbbbbbbbbbbbbb {\n"
+ "}",
+ InheritanceStyle);
+ InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
+ verifyFormat("class Foooooooooooooooooooooo\n"
+ " : public aaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbb {\n"
+ "}",
+ InheritanceStyle);
+ InheritanceStyle.ConstructorInitializerIndentWidth = 0;
+ verifyFormat("class Foooooooooooooooooooooo\n"
+ ": public aaaaaaaaaaaaaaaaaa,\n"
+ " public bbbbbbbbbbbbbbbbbb {}",
+ InheritanceStyle);
+
+ FormatStyle ForLoopStyle = getLLVMStyle();
+ ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
+ verifyFormat("class Foo : public Bar {};", ForLoopStyle);
+ verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
+ verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
+ verifyFormat("int x = a ? b : c;", ForLoopStyle);
+ verifyFormat("{\n"
+ "label2:\n"
+ " int x = 0;\n"
+ "}",
+ ForLoopStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ "default:\n"
+ "}",
+ ForLoopStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1: {\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default: {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ ForLoopStyle);
+
+ FormatStyle CaseStyle = getLLVMStyle();
+ CaseStyle.SpaceBeforeCaseColon = true;
+ verifyFormat("class Foo : public Bar {};", CaseStyle);
+ verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
+ verifyFormat("for (auto a : b) {\n}", CaseStyle);
+ verifyFormat("int x = a ? b : c;", CaseStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1 :\n"
+ "default :\n"
+ "}",
+ CaseStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1 : {\n"
+ " break;\n"
+ "}\n"
+ "case 2 : {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default : {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ CaseStyle);
+ // Goto labels should not be affected.
+ verifyFormat("switch (x) {\n"
+ "goto_label:\n"
+ "default :\n"
+ "}",
+ CaseStyle);
+ verifyFormat("switch (x) {\n"
+ "goto_label: { break; }\n"
+ "default : {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ CaseStyle);
+
+ FormatStyle NoSpaceStyle = getLLVMStyle();
+ EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
+ NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
+ NoSpaceStyle.SpaceBeforeInheritanceColon = false;
+ NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
+ verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
+ verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
+ verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
+ verifyFormat("int x = a ? b : c;", NoSpaceStyle);
+ verifyFormat("{\n"
+ "label3:\n"
+ " int x = 0;\n"
+ "}",
+ NoSpaceStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1:\n"
+ "default:\n"
+ "}",
+ NoSpaceStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1: {\n"
+ " break;\n"
+ "}\n"
+ "case 2: {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default: {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ NoSpaceStyle);
+
+ FormatStyle InvertedSpaceStyle = getLLVMStyle();
+ InvertedSpaceStyle.SpaceBeforeCaseColon = true;
+ InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
+ InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
+ InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
+ verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
+ verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
+ verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
+ verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
+ verifyFormat("{\n"
+ "label3:\n"
+ " int x = 0;\n"
+ "}",
+ InvertedSpaceStyle);
+ verifyFormat("switch (x) {\n"
+ "case 1 :\n"
+ "case 2 : {\n"
+ " break;\n"
+ "}\n"
+ "default :\n"
+ " break;\n"
+ "}",
+ InvertedSpaceStyle);
+ verifyFormat("switch (allBraces) {\n"
+ "case 1 : {\n"
+ " break;\n"
+ "}\n"
+ "case 2 : {\n"
+ " [[fallthrough]];\n"
+ "}\n"
+ "default : {\n"
+ " break;\n"
+ "}\n"
+ "}",
+ InvertedSpaceStyle);
+}
+
+TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
+ FormatStyle Style = getLLVMStyle();
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
+ verifyFormat("void* const* x = NULL;", Style);
+
+#define verifyQualifierSpaces(Code, Pointers, Qualifiers) \
+ do { \
+ Style.PointerAlignment = FormatStyle::Pointers; \
+ Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \
+ verifyFormat(Code, Style); \
+ } while (false)
+
+ verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
+ verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
+ verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
+
+ verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
+ verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
+ verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
+
+ verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
+ verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
+ verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
+
+ verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
+ verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
+ verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
+
+ verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
+ SAPQ_Default);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
+ SAPQ_Default);
+
+ verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
+ SAPQ_Before);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
+ SAPQ_Before);
+
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
+ SAPQ_After);
+
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
+ verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
+
+#undef verifyQualifierSpaces
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.AttributeMacros.push_back("qualified");
+ Spaces.PointerAlignment = FormatStyle::PAS_Right;
+ Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
+ verifyFormat("SomeType *volatile *a = NULL;", Spaces);
+ verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("std::vector<SomeType *const *> x;", Spaces);
+ verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
+ verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
+ Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
+ verifyFormat("SomeType * volatile *a = NULL;", Spaces);
+ verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
+ verifyFormat("std::vector<SomeType * const *> x;", Spaces);
+ verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
+ verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
+
+ // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
+ Spaces.PointerAlignment = FormatStyle::PAS_Left;
+ Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
+ verifyFormat("SomeType* volatile* a = NULL;", Spaces);
+ verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
+ verifyFormat("std::vector<SomeType* const*> x;", Spaces);
+ verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
+ verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
+ // However, setting it to SAPQ_After should add spaces after __attribute, etc.
+ Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
+ verifyFormat("SomeType* volatile * a = NULL;", Spaces);
+ verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
+ verifyFormat("std::vector<SomeType* const *> x;", Spaces);
+ verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
+ verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
+
+ // PAS_Middle should not have any noticeable changes even for SAPQ_Both
+ Spaces.PointerAlignment = FormatStyle::PAS_Middle;
+ Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
+ verifyFormat("SomeType * volatile * a = NULL;", Spaces);
+ verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
+ verifyFormat("std::vector<SomeType * const *> x;", Spaces);
+ verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
+ verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
+}
+
+TEST_F(FormatTest, LinuxBraceBreaking) {
+ FormatStyle LinuxBraceStyle = getLLVMStyle();
+ LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
+ verifyFormat("namespace a\n"
+ "{\n"
+ "class A\n"
+ "{\n"
+ " void f()\n"
+ " {\n"
+ " if (true) {\n"
+ " a();\n"
+ " b();\n"
+ " } else {\n"
+ " a();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "};\n"
+ "struct B {\n"
+ " int x;\n"
+ "};\n"
+ "} // namespace a",
+ LinuxBraceStyle);
+ verifyFormat("enum X {\n"
+ " Y = 0,\n"
+ "}",
+ LinuxBraceStyle);
+ verifyFormat("struct S {\n"
+ " int Type;\n"
+ " union {\n"
+ " int x;\n"
+ " double y;\n"
+ " } Value;\n"
+ " class C\n"
+ " {\n"
+ " MyFavoriteType Value;\n"
+ " } Class;\n"
+ "}",
+ LinuxBraceStyle);
+}
+
+TEST_F(FormatTest, MozillaBraceBreaking) {
+ FormatStyle MozillaBraceStyle = getLLVMStyle();
+ MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
+ MozillaBraceStyle.FixNamespaceComments = false;
+ verifyFormat("namespace a {\n"
+ "class A\n"
+ "{\n"
+ " void f()\n"
+ " {\n"
+ " if (true) {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "};\n"
+ "enum E\n"
+ "{\n"
+ " A,\n"
+ " // foo\n"
+ " B,\n"
+ " C\n"
+ "};\n"
+ "struct B\n"
+ "{\n"
+ " int x;\n"
+ "};\n"
+ "}",
+ MozillaBraceStyle);
+ verifyFormat("struct S\n"
+ "{\n"
+ " int Type;\n"
+ " union\n"
+ " {\n"
+ " int x;\n"
+ " double y;\n"
+ " } Value;\n"
+ " class C\n"
+ " {\n"
+ " MyFavoriteType Value;\n"
+ " } Class;\n"
+ "}",
+ MozillaBraceStyle);
+}
+
+TEST_F(FormatTest, StroustrupBraceBreaking) {
+ FormatStyle StroustrupBraceStyle = getLLVMStyle();
+ StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
+ verifyFormat("namespace a {\n"
+ "class A {\n"
+ " void f()\n"
+ " {\n"
+ " if (true) {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "};\n"
+ "struct B {\n"
+ " int x;\n"
+ "};\n"
+ "} // namespace a",
+ StroustrupBraceStyle);
+
+ verifyFormat("void foo()\n"
+ "{\n"
+ " if (a) {\n"
+ " a();\n"
+ " }\n"
+ " else {\n"
+ " b();\n"
+ " }\n"
+ "}",
+ StroustrupBraceStyle);
+
+ verifyFormat("#ifdef _DEBUG\n"
+ "int foo(int i = 0)\n"
+ "#else\n"
+ "int foo(int i = 5)\n"
+ "#endif\n"
+ "{\n"
+ " return i;\n"
+ "}",
+ StroustrupBraceStyle);
+
+ verifyFormat("void foo() {}\n"
+ "void bar()\n"
+ "#ifdef _DEBUG\n"
+ "{\n"
+ " foo();\n"
+ "}\n"
+ "#else\n"
+ "{\n"
+ "}\n"
+ "#endif",
+ StroustrupBraceStyle);
+
+ verifyFormat("void foobar() { int i = 5; }\n"
+ "#ifdef _DEBUG\n"
+ "void bar() {}\n"
+ "#else\n"
+ "void bar() { foobar(); }\n"
+ "#endif",
+ StroustrupBraceStyle);
+}
+
+TEST_F(FormatTest, AllmanBraceBreaking) {
+ FormatStyle AllmanBraceStyle = getLLVMStyle();
+ AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
+
+ verifyFormat("namespace a\n"
+ "{\n"
+ "void f();\n"
+ "void g();\n"
+ "} // namespace a",
+ "namespace a\n"
+ "{\n"
+ "void f();\n"
+ "void g();\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("namespace a\n"
+ "{\n"
+ "class A\n"
+ "{\n"
+ " void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "};\n"
+ "struct B\n"
+ "{\n"
+ " int x;\n"
+ "};\n"
+ "union C\n"
+ "{\n"
+ "};\n"
+ "} // namespace a",
+ AllmanBraceStyle);
+
+ verifyFormat("void f()\n"
+ "{\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " else if (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " else\n"
+ " {\n"
+ " c();\n"
+ " }\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("void f()\n"
+ "{\n"
+ " for (int i = 0; i < 10; ++i)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " while (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " do\n"
+ " {\n"
+ " c();\n"
+ " } while (false)\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("void f(int a)\n"
+ "{\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " break;\n"
+ " case 1:\n"
+ " {\n"
+ " break;\n"
+ " }\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " break;\n"
+ " }\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("enum X\n"
+ "{\n"
+ " Y = 0,\n"
+ "}",
+ AllmanBraceStyle);
+ verifyFormat("enum X\n"
+ "{\n"
+ " Y = 0\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("@interface BSApplicationController ()\n"
+ "{\n"
+ "@private\n"
+ " id _extraIvar;\n"
+ "}\n"
+ "@end",
+ AllmanBraceStyle);
+
+ verifyFormat("#ifdef _DEBUG\n"
+ "int foo(int i = 0)\n"
+ "#else\n"
+ "int foo(int i = 5)\n"
+ "#endif\n"
+ "{\n"
+ " return i;\n"
+ "}",
+ AllmanBraceStyle);
+
+ verifyFormat("void foo() {}\n"
+ "void bar()\n"
+ "#ifdef _DEBUG\n"
+ "{\n"
+ " foo();\n"
+ "}\n"
+ "#else\n"
+ "{\n"
+ "}\n"
+ "#endif",
+ AllmanBraceStyle);
+
+ verifyFormat("void foobar() { int i = 5; }\n"
+ "#ifdef _DEBUG\n"
+ "void bar() {}\n"
+ "#else\n"
+ "void bar() { foobar(); }\n"
+ "#endif",
+ AllmanBraceStyle);
+
+ EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
+ FormatStyle::SLS_All);
+
+ verifyFormat("[](int i) { return i + 2; };\n"
+ "[](int i, int j)\n"
+ "{\n"
+ " auto x = i + j;\n"
+ " auto y = i * j;\n"
+ " return x ^ y;\n"
+ "};\n"
+ "void foo()\n"
+ "{\n"
+ " auto shortLambda = [](int i) { return i + 2; };\n"
+ " auto longLambda = [](int i, int j)\n"
+ " {\n"
+ " auto x = i + j;\n"
+ " auto y = i * j;\n"
+ " return x ^ y;\n"
+ " };\n"
+ "}",
+ AllmanBraceStyle);
+
+ AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+
+ verifyFormat("[](int i)\n"
+ "{\n"
+ " return i + 2;\n"
+ "};\n"
+ "[](int i, int j)\n"
+ "{\n"
+ " auto x = i + j;\n"
+ " auto y = i * j;\n"
+ " return x ^ y;\n"
+ "};\n"
+ "void foo()\n"
+ "{\n"
+ " auto shortLambda = [](int i)\n"
+ " {\n"
+ " return i + 2;\n"
+ " };\n"
+ " auto longLambda = [](int i, int j)\n"
+ " {\n"
+ " auto x = i + j;\n"
+ " auto y = i * j;\n"
+ " return x ^ y;\n"
+ " };\n"
+ "}",
+ AllmanBraceStyle);
+
+ // Reset
+ AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
+
+ // This shouldn't affect ObjC blocks..
+ verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
+ " // ...\n"
+ " int i;\n"
+ "}];",
+ AllmanBraceStyle);
+ verifyFormat("void (^block)(void) = ^{\n"
+ " // ...\n"
+ " int i;\n"
+ "};",
+ AllmanBraceStyle);
+ // .. or dict literals.
+ verifyFormat("void f()\n"
+ "{\n"
+ " // ...\n"
+ " [object someMethod:@{@\"a\" : @\"b\"}];\n"
+ "}",
+ AllmanBraceStyle);
+ verifyFormat("void f()\n"
+ "{\n"
+ " // ...\n"
+ " [object someMethod:@{a : @\"b\"}];\n"
+ "}",
+ AllmanBraceStyle);
+ verifyFormat("int f()\n"
+ "{ // comment\n"
+ " return 42;\n"
+ "}",
+ AllmanBraceStyle);
+
+ AllmanBraceStyle.ColumnLimit = 19;
+ verifyFormat("void f() { int i; }", AllmanBraceStyle);
+ AllmanBraceStyle.ColumnLimit = 18;
+ verifyFormat("void f()\n"
+ "{\n"
+ " int i;\n"
+ "}",
+ AllmanBraceStyle);
+ AllmanBraceStyle.ColumnLimit = 80;
+
+ FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
+ BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_WithoutElse;
+ BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if constexpr (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if CONSTEXPR (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if (b) return;\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if constexpr (b) return;\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " if CONSTEXPR (b) return;\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ "{\n"
+ " while (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ "}",
+ BreakBeforeBraceShortIfs);
+}
+
+TEST_F(FormatTest, WhitesmithsBraceBreaking) {
+ FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
+ WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
+
+ // Make a few changes to the style for testing purposes
+ WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setEmptyOnly();
+ WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+
+ // FIXME: this test case can't decide whether there should be a blank line
+ // after the ~D() line or not. It adds one if one doesn't exist in the test
+ // and it removes the line if one exists.
+ /*
+ verifyFormat("class A;\n"
+ "namespace B\n"
+ " {\n"
+ "class C;\n"
+ "// Comment\n"
+ "class D\n"
+ " {\n"
+ "public:\n"
+ " D();\n"
+ " ~D() {}\n"
+ "private:\n"
+ " enum E\n"
+ " {\n"
+ " F\n"
+ " }\n"
+ " };\n"
+ " } // namespace B",
+ WhitesmithsBraceStyle);
+ */
+
+ WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
+ verifyFormat("namespace a\n"
+ " {\n"
+ "class A\n"
+ " {\n"
+ " void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g()\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " };\n"
+ "struct B\n"
+ " {\n"
+ " int x;\n"
+ " };\n"
+ " } // namespace a",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("namespace a\n"
+ " {\n"
+ "namespace b\n"
+ " {\n"
+ "class A\n"
+ " {\n"
+ " void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g()\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " };\n"
+ "struct B\n"
+ " {\n"
+ " int x;\n"
+ " };\n"
+ " } // namespace b\n"
+ " } // namespace a",
+ WhitesmithsBraceStyle);
+
+ WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
+ verifyFormat("namespace a\n"
+ " {\n"
+ "namespace b\n"
+ " {\n"
+ " class A\n"
+ " {\n"
+ " void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g()\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " };\n"
+ " struct B\n"
+ " {\n"
+ " int x;\n"
+ " };\n"
+ " } // namespace b\n"
+ " } // namespace a",
+ WhitesmithsBraceStyle);
+
+ WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
+ verifyFormat("namespace a\n"
+ " {\n"
+ " namespace b\n"
+ " {\n"
+ " class A\n"
+ " {\n"
+ " void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g()\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " };\n"
+ " struct B\n"
+ " {\n"
+ " int x;\n"
+ " };\n"
+ " } // namespace b\n"
+ " } // namespace a",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void f()\n"
+ " {\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " else if (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " else\n"
+ " {\n"
+ " c();\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void f()\n"
+ " {\n"
+ " for (int i = 0; i < 10; ++i)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " while (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " do\n"
+ " {\n"
+ " c();\n"
+ " } while (false)\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ WhitesmithsBraceStyle.IndentCaseLabels = true;
+ verifyFormat("void switchTest1(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void switchTest2(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " break;\n"
+ " case 1:\n"
+ " {\n"
+ " break;\n"
+ " }\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void switchTest3(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " {\n"
+ " foo(x);\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " {\n"
+ " foo(1);\n"
+ " }\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ WhitesmithsBraceStyle.IndentCaseLabels = false;
+
+ verifyFormat("void switchTest4(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void switchTest5(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " break;\n"
+ " case 1:\n"
+ " {\n"
+ " foo();\n"
+ " break;\n"
+ " }\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void switchTest6(int a)\n"
+ " {\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " {\n"
+ " foo(x);\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " {\n"
+ " foo(1);\n"
+ " }\n"
+ " break;\n"
+ " }\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("enum X\n"
+ " {\n"
+ " Y = 0, // testing\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("enum X\n"
+ " {\n"
+ " Y = 0\n"
+ " }",
+ WhitesmithsBraceStyle);
+ verifyFormat("enum X\n"
+ " {\n"
+ " Y = 0,\n"
+ " Z = 1\n"
+ " };\n"
+ "int i;",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("@interface BSApplicationController ()\n"
+ " {\n"
+ "@private\n"
+ " id _extraIvar;\n"
+ " }\n"
+ "@end",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("#ifdef _DEBUG\n"
+ "int foo(int i = 0)\n"
+ "#else\n"
+ "int foo(int i = 5)\n"
+ "#endif\n"
+ " {\n"
+ " return i;\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void foo() {}\n"
+ "void bar()\n"
+ "#ifdef _DEBUG\n"
+ " {\n"
+ " foo();\n"
+ " }\n"
+ "#else\n"
+ " {\n"
+ " }\n"
+ "#endif",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("void foobar()\n"
+ " {\n"
+ " int i = 5;\n"
+ " }\n"
+ "#ifdef _DEBUG\n"
+ "void bar() {}\n"
+ "#else\n"
+ "void bar()\n"
+ " {\n"
+ " foobar();\n"
+ " }\n"
+ "#endif",
+ WhitesmithsBraceStyle);
+
+ // This shouldn't affect ObjC blocks..
+ verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
+ " // ...\n"
+ " int i;\n"
+ "}];",
+ WhitesmithsBraceStyle);
+ verifyFormat("void (^block)(void) = ^{\n"
+ " // ...\n"
+ " int i;\n"
+ "};",
+ WhitesmithsBraceStyle);
+ // .. or dict literals.
+ verifyFormat("void f()\n"
+ " {\n"
+ " [object someMethod:@{@\"a\" : @\"b\"}];\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ verifyFormat("int f()\n"
+ " { // comment\n"
+ " return 42;\n"
+ " }",
+ WhitesmithsBraceStyle);
+
+ FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
+ BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
+ FormatStyle::SIS_OnlyFirstIf;
+ BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
+ verifyFormat("void f(bool b)\n"
+ " {\n"
+ " if (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " }",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ " {\n"
+ " if (b) return;\n"
+ " }",
+ BreakBeforeBraceShortIfs);
+ verifyFormat("void f(bool b)\n"
+ " {\n"
+ " while (b)\n"
+ " {\n"
+ " return;\n"
+ " }\n"
+ " }",
+ BreakBeforeBraceShortIfs);
+}
+
+TEST_F(FormatTest, GNUBraceBreaking) {
+ FormatStyle GNUBraceStyle = getLLVMStyle();
+ GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
+ verifyFormat("namespace a\n"
+ "{\n"
+ "class A\n"
+ "{\n"
+ " void f()\n"
+ " {\n"
+ " int a;\n"
+ " {\n"
+ " int b;\n"
+ " }\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "}\n"
+ "} // namespace a",
+ GNUBraceStyle);
+
+ verifyFormat("void f()\n"
+ "{\n"
+ " if (true)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " else if (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " else\n"
+ " {\n"
+ " c();\n"
+ " }\n"
+ "}",
+ GNUBraceStyle);
+
+ verifyFormat("void f()\n"
+ "{\n"
+ " for (int i = 0; i < 10; ++i)\n"
+ " {\n"
+ " a();\n"
+ " }\n"
+ " while (false)\n"
+ " {\n"
+ " b();\n"
+ " }\n"
+ " do\n"
+ " {\n"
+ " c();\n"
+ " }\n"
+ " while (false);\n"
+ "}",
+ GNUBraceStyle);
+
+ verifyFormat("void f(int a)\n"
+ "{\n"
+ " switch (a)\n"
+ " {\n"
+ " case 0:\n"
+ " break;\n"
+ " case 1:\n"
+ " {\n"
+ " break;\n"
+ " }\n"
+ " case 2:\n"
+ " {\n"
+ " }\n"
+ " break;\n"
+ " default:\n"
+ " break;\n"
+ " }\n"
+ "}",
+ GNUBraceStyle);
+
+ verifyFormat("enum X\n"
+ "{\n"
+ " Y = 0,\n"
+ "}",
+ GNUBraceStyle);
+
+ verifyFormat("@interface BSApplicationController ()\n"
+ "{\n"
+ "@private\n"
+ " id _extraIvar;\n"
+ "}\n"
+ "@end",
+ GNUBraceStyle);
+
+ verifyFormat("#ifdef _DEBUG\n"
+ "int foo(int i = 0)\n"
+ "#else\n"
+ "int foo(int i = 5)\n"
+ "#endif\n"
+ "{\n"
+ " return i;\n"
+ "}",
+ GNUBraceStyle);
+
+ verifyFormat("void foo() {}\n"
+ "void bar()\n"
+ "#ifdef _DEBUG\n"
+ "{\n"
+ " foo();\n"
+ "}\n"
+ "#else\n"
+ "{\n"
+ "}\n"
+ "#endif",
+ GNUBraceStyle);
+
+ verifyFormat("void foobar() { int i = 5; }\n"
+ "#ifdef _DEBUG\n"
+ "void bar() {}\n"
+ "#else\n"
+ "void bar() { foobar(); }\n"
+ "#endif",
+ GNUBraceStyle);
+}
+
+TEST_F(FormatTest, WebKitBraceBreaking) {
+ FormatStyle WebKitBraceStyle = getLLVMStyle();
+ WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
+ WebKitBraceStyle.FixNamespaceComments = false;
+ verifyFormat("namespace a {\n"
+ "class A {\n"
+ " void f()\n"
+ " {\n"
+ " if (true) {\n"
+ " a();\n"
+ " b();\n"
+ " }\n"
+ " }\n"
+ " void g() { return; }\n"
+ "};\n"
+ "enum E {\n"
+ " A,\n"
+ " // foo\n"
+ " B,\n"
+ " C\n"
+ "};\n"
+ "struct B {\n"
+ " int x;\n"
+ "};\n"
+ "}",
+ WebKitBraceStyle);
+ verifyFormat("struct S {\n"
+ " int Type;\n"
+ " union {\n"
+ " int x;\n"
+ " double y;\n"
+ " } Value;\n"
+ " class C {\n"
+ " MyFavoriteType Value;\n"
+ " } Class;\n"
+ "};",
+ WebKitBraceStyle);
+}
+
+TEST_F(FormatTest, CatchExceptionReferenceBinding) {
+ verifyFormat("void f() {\n"
+ " try {\n"
+ " } catch (const Exception &e) {\n"
+ " }\n"
+ "}");
+}
+
+TEST_F(FormatTest, UnderstandsPragmas) {
+ verifyFormat("#pragma omp reduction(| : var)");
+ verifyFormat("#pragma omp reduction(+ : var)");
+
+ verifyFormat("#pragma mark Any non-hyphenated or hyphenated string "
+ "(including parentheses).",
+ "#pragma mark Any non-hyphenated or hyphenated string "
+ "(including parentheses).");
+
+ verifyFormat("#pragma mark Any non-hyphenated or hyphenated string "
+ "(including parentheses).",
+ "#pragma mark Any non-hyphenated or hyphenated string "
+ "(including parentheses).");
+
+ verifyFormat("#pragma comment(linker, \\\n"
+ " \"argument\" \\\n"
+ " \"argument\"",
+ "#pragma comment(linker, \\\n"
+ " \"argument\" \\\n"
+ " \"argument\"",
+ getStyleWithColumns(getChromiumStyle(FormatStyle::LK_Cpp), 32));
+}
+
+TEST_F(FormatTest, UnderstandsPragmaOmpTarget) {
+ verifyFormat("#pragma omp target map(to : var)");
+ verifyFormat("#pragma omp target map(to : var[ : N])");
+ verifyFormat("#pragma omp target map(to : var[0 : N])");
+ verifyFormat("#pragma omp target map(always, to : var[0 : N])");
+
+ verifyFormat(
+ "#pragma omp target \\\n"
+ " reduction(+ : var) \\\n"
+ " map(to : A[0 : N]) \\\n"
+ " map(to : B[0 : N]) \\\n"
+ " map(from : C[0 : N]) \\\n"
+ " firstprivate(i) \\\n"
+ " firstprivate(j) \\\n"
+ " firstprivate(k)",
+ "#pragma omp target reduction(+:var) map(to:A[0:N]) map(to:B[0:N]) "
+ "map(from:C[0:N]) firstprivate(i) firstprivate(j) firstprivate(k)",
+ getLLVMStyleWithColumns(26));
+}
+
+TEST_F(FormatTest, UnderstandPragmaOption) {
+ verifyFormat("#pragma option -C -A");
+
+ verifyFormat("#pragma option -C -A", "#pragma option -C -A");
+}
+
+TEST_F(FormatTest, UnderstandPragmaRegion) {
+ auto Style = getLLVMStyleWithColumns(0);
+ verifyFormat("#pragma region TEST(FOO : BAR)", Style);
+ verifyFormat("#pragma region TEST(FOO: NOSPACE)", Style);
+}
+
+TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
+ FormatStyle Style = getLLVMStyleWithColumns(20);
+
+ // See PR41213
+ verifyFormat("/*\n"
+ " *\t9012345\n"
+ " * /8901\n"
+ " */",
+ "/*\n"
+ " *\t9012345 /8901\n"
+ " */",
+ Style);
+ verifyFormat("/*\n"
+ " *345678\n"
+ " *\t/8901\n"
+ " */",
+ "/*\n"
+ " *345678\t/8901\n"
+ " */",
+ Style);
+
+ verifyFormat("int a; // the\n"
+ " // comment",
+ Style);
+ verifyNoChange("int a; /* first line\n"
+ " * second\n"
+ " * line third\n"
+ " * line\n"
+ " */",
+ Style);
+ verifyFormat("int a; // first line\n"
+ " // second\n"
+ " // line third\n"
+ " // line",
+ "int a; // first line\n"
+ " // second line\n"
+ " // third line",
+ Style);
+
+ Style.PenaltyExcessCharacter = 90;
+ verifyFormat("int a; // the comment", Style);
+ verifyFormat("int a; // the comment\n"
+ " // aaa",
+ "int a; // the comment aaa", Style);
+ verifyNoChange("int a; /* first line\n"
+ " * second line\n"
+ " * third line\n"
+ " */",
+ Style);
+ verifyFormat("int a; // first line\n"
+ " // second line\n"
+ " // third line",
+ Style);
+ // FIXME: Investigate why this is not getting the same layout as the test
+ // above.
+ verifyFormat("int a; /* first line\n"
+ " * second line\n"
+ " * third line\n"
+ " */",
+ "int a; /* first line second line third line"
+ "\n*/",
+ Style);
+
+ verifyFormat("// foo bar baz bazfoo\n"
+ "// foo bar foo bar",
+ "// foo bar baz bazfoo\n"
+ "// foo bar foo bar",
+ Style);
+ verifyFormat("// foo bar baz bazfoo\n"
+ "// foo bar foo bar",
+ "// foo bar baz bazfoo\n"
+ "// foo bar foo bar",
+ Style);
+
+ // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
+ // next one.
+ verifyFormat("// foo bar baz bazfoo\n"
+ "// bar foo bar",
+ "// foo bar baz bazfoo bar\n"
+ "// foo bar",
+ Style);
+
+ // FIXME: unstable test case
+ EXPECT_EQ("// foo bar baz bazfoo\n"
+ "// foo bar baz bazfoo\n"
+ "// bar foo bar",
+ format("// foo bar baz bazfoo\n"
+ "// foo bar baz bazfoo bar\n"
+ "// foo bar",
+ Style));
+
+ // FIXME: unstable test case
+ EXPECT_EQ("// foo bar baz bazfoo\n"
+ "// foo bar baz bazfoo\n"
+ "// bar foo bar",
+ format("// foo bar baz bazfoo\n"
+ "// foo bar baz bazfoo bar\n"
+ "// foo bar",
+ Style));
+
+ // Make sure we do not keep protruding characters if strict mode reflow is
+ // cheaper than keeping protruding characters.
+ Style.ColumnLimit = 21;
+ verifyFormat("// foo foo foo foo\n"
+ "// foo foo foo foo\n"
+ "// foo foo foo foo",
+ "// foo foo foo foo foo foo foo foo foo foo foo foo", Style);
+
+ verifyFormat("int a = /* long block\n"
+ " comment */\n"
+ " 42;",
+ "int a = /* long block comment */ 42;", Style);
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterLParen) {
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 8;
+ Style.PenaltyExcessCharacter = 15;
+ verifyFormat("int foo(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+ Style.PenaltyBreakOpenParenthesis = 200;
+ verifyFormat("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
+ "int foo(\n"
+ " int aaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 5;
+ Style.PenaltyExcessCharacter = 150;
+ verifyFormat("foo((\n"
+ " int)aaaaaaaaaaaaaaaaaaaaaaaa);",
+
+ Style);
+ Style.PenaltyBreakOpenParenthesis = 100'000;
+ verifyFormat("foo((int)\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaa);",
+ "foo((\n"
+ "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 4;
+ Style.PenaltyExcessCharacter = 100;
+ verifyFormat("for (\n"
+ " int iiiiiiiiiiiiiiiii =\n"
+ " 0;\n"
+ " iiiiiiiiiiiiiiiii <\n"
+ " 2;\n"
+ " iiiiiiiiiiiiiiiii++) {\n"
+ "}",
+
+ Style);
+ Style.PenaltyBreakOpenParenthesis = 1250;
+ verifyFormat("for (int iiiiiiiiiiiiiiiii =\n"
+ " 0;\n"
+ " iiiiiiiiiiiiiiiii <\n"
+ " 2;\n"
+ " iiiiiiiiiiiiiiiii++) {\n"
+ "}",
+ "for (\n"
+ " int iiiiiiiiiiiiiiiii =\n"
+ " 0;\n"
+ " iiiiiiiiiiiiiiiii <\n"
+ " 2;\n"
+ " iiiiiiiiiiiiiiiii++) {\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, BreakPenaltyBeforeMemberAccess) {
+ auto Style = getLLVMStyle();
+ EXPECT_EQ(Style.PenaltyBreakBeforeMemberAccess, 150u);
+
+ Style.ColumnLimit = 60;
+ Style.PenaltyBreakBeforeMemberAccess = 110;
+ verifyFormat("aaaaaaaa.aaaaaaaa.bbbbbbbb()\n"
+ " .ccccccccccccccccccccc(dddddddd);\n"
+ "aaaaaaaa.aaaaaaaa\n"
+ " .bbbbbbbb(cccccccccccccccccccccccccccccccc);",
+ Style);
+
+ Style.ColumnLimit = 13;
+ verifyFormat("foo->bar\n"
+ " .b(a);",
+ Style);
+}
+
+TEST_F(FormatTest, BreakPenaltyScopeResolution) {
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 20;
+ Style.PenaltyExcessCharacter = 100;
+ verifyFormat("unsigned long\n"
+ "foo::bar();",
+ Style);
+ Style.PenaltyBreakScopeResolution = 10;
+ verifyFormat("unsigned long foo::\n"
+ " bar();",
+ Style);
+}
+
+TEST_F(FormatTest, WorksFor8bitEncodings) {
+ // FIXME: unstable test case
+ EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
+ "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
+ "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
+ "\"\xef\xee\xf0\xf3...\"",
+ format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
+ "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
+ "\xef\xee\xf0\xf3...\"",
+ getLLVMStyleWithColumns(12)));
+}
+
+TEST_F(FormatTest, HandlesUTF8BOM) {
+ verifyFormat("\xef\xbb\xbf");
+ verifyFormat("\xef\xbb\xbf#include <iostream>");
+ verifyFormat("\xef\xbb\xbf\n#include <iostream>");
+
+ auto Style = getLLVMStyle();
+ Style.KeepEmptyLines.AtStartOfFile = false;
+ verifyFormat("\xef\xbb\xbf#include <iostream>",
+ "\xef\xbb\xbf\n#include <iostream>", Style);
+}
+
+// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
+#if !defined(_MSC_VER)
+
+TEST_F(FormatTest, CountsUTF8CharactersProperly) {
+ verifyFormat("\"Однажды в студёную зимнюю пору...\"",
+ getLLVMStyleWithColumns(35));
+ verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
+ getLLVMStyleWithColumns(31));
+ verifyFormat("// Однажды в студёную зимнюю пору...",
+ getLLVMStyleWithColumns(36));
+ verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
+ verifyFormat("/* Однажды в студёную зимнюю пору... */",
+ getLLVMStyleWithColumns(39));
+ verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
+ getLLVMStyleWithColumns(35));
+}
+
+TEST_F(FormatTest, SplitsUTF8Strings) {
+ // Non-printable characters' width is currently considered to be the length in
+ // bytes in UTF8. The characters can be displayed in very different manner
+ // (zero-width, single width with a substitution glyph, expanded to their code
+ // (e.g. "<8d>"), so there's no single correct way to handle them.
+ // FIXME: unstable test case
+ EXPECT_EQ("\"aaaaÄ\"\n"
+ "\"\xc2\x8d\";",
+ format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"aaaaaaaÄ\"\n"
+ "\"\xc2\x8d\";",
+ format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"Однажды, в \"\n"
+ "\"студёную \"\n"
+ "\"зимнюю \"\n"
+ "\"пору,\"",
+ format("\"Однажды, в студёную зимнюю пору,\"",
+ getLLVMStyleWithColumns(13)));
+ // FIXME: unstable test case
+ EXPECT_EQ(
+ "\"一 二 三 \"\n"
+ "\"四 五六 \"\n"
+ "\"七 八 九 \"\n"
+ "\"十\"",
+ format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
+ // FIXME: unstable test case
+ EXPECT_EQ("\"一\t\"\n"
+ "\"二 \t\"\n"
+ "\"三 四 \"\n"
+ "\"五\t\"\n"
+ "\"六 \t\"\n"
+ "\"七 \"\n"
+ "\"八九十\tqq\"",
+ format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
+ getLLVMStyleWithColumns(11)));
+
+ // UTF8 character in an escape sequence.
+ // FIXME: unstable test case
+ EXPECT_EQ("\"aaaaaa\"\n"
+ "\"\\\xC2\x8D\"",
+ format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
+}
+
+TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
+ verifyFormat("const char *sssss =\n"
+ " \"一二三四五六七八\\\n"
+ " 九 十\";",
+ "const char *sssss = \"一二三四五六七八\\\n"
+ " 九 十\";",
+ getLLVMStyleWithColumns(30));
+}
+
+TEST_F(FormatTest, SplitsUTF8LineComments) {
+ verifyFormat("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10));
+ verifyFormat("// Я из лесу\n"
+ "// вышел; был\n"
+ "// сильный\n"
+ "// мороз.",
+ "// Я из лесу вышел; был сильный мороз.",
+ getLLVMStyleWithColumns(13));
+ verifyFormat("// 一二三\n"
+ "// 四五六七\n"
+ "// 八 九\n"
+ "// 十",
+ "// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9));
+}
+
+TEST_F(FormatTest, SplitsUTF8BlockComments) {
+ verifyFormat("/* Гляжу,\n"
+ " * поднимается\n"
+ " * медленно в\n"
+ " * гору\n"
+ " * Лошадка,\n"
+ " * везущая\n"
+ " * хворосту\n"
+ " * воз. */",
+ "/* Гляжу, поднимается медленно в гору\n"
+ " * Лошадка, везущая хворосту воз. */",
+ getLLVMStyleWithColumns(13));
+ verifyFormat("/* 一二三\n"
+ " * 四五六七\n"
+ " * 八 九\n"
+ " * 十 */",
+ "/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9));
+ verifyFormat("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯\n"
+ " * 𝕓𝕪𝕥𝕖\n"
+ " * 𝖀𝕿𝕱-𝟠 */",
+ "/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯 𝕓𝕪𝕥𝕖 𝖀𝕿𝕱-𝟠 */", getLLVMStyleWithColumns(12));
+}
+
+#endif // _MSC_VER
+
+TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
+ FormatStyle Style = getLLVMStyle();
+
+ Style.ConstructorInitializerIndentWidth = 4;
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+
+ Style.ConstructorInitializerIndentWidth = 2;
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+
+ Style.ConstructorInitializerIndentWidth = 0;
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
+ " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
+ Style);
+ Style.BreakAfterOpenBracketFunction = true;
+ verifyFormat(
+ "SomeLongTemplateVariableName<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
+ Style);
+ verifyFormat("bool smaller = 1 < "
+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
+ " "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
+
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
+ verifyFormat("SomeClass::Constructor() :\n"
+ "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
+ "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
+ Style);
+}
+
+TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ Style.ConstructorInitializerIndentWidth = 4;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ " , b(b)\n"
+ " , c(c) {}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a) {}",
+ Style);
+
+ Style.ColumnLimit = 0;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a) {}",
+ Style);
+ verifyFormat("SomeClass::Constructor() noexcept\n"
+ " : a(a) {}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ " , b(b)\n"
+ " , c(c) {}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a) {\n"
+ " foo();\n"
+ " bar();\n"
+ "}",
+ Style);
+
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ " , b(b)\n"
+ " , c(c) {\n}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a) {\n}",
+ Style);
+
+ Style.ColumnLimit = 80;
+ Style.AllowShortFunctionsOnASingleLine =
+ FormatStyle::ShortFunctionStyle::setAll();
+ Style.ConstructorInitializerIndentWidth = 2;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ " , b(b)\n"
+ " , c(c) {}",
+ Style);
+
+ Style.ConstructorInitializerIndentWidth = 0;
+ verifyFormat("SomeClass::Constructor()\n"
+ ": a(a)\n"
+ ", b(b)\n"
+ ", c(c) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ Style.ConstructorInitializerIndentWidth = 4;
+ verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
+ verifyFormat(
+ "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)",
+ Style);
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
+ Style);
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaaaaa(aaaaaaaa) {}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)",
+ Style);
+ verifyFormat(
+ "SomeClass::Constructor()\n"
+ " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
+ Style);
+
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
+ Style.ConstructorInitializerIndentWidth = 4;
+ Style.ColumnLimit = 60;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaaaaa(aaaaaaaa)\n"
+ " , aaaaaaaa(aaaaaaaa)\n"
+ " , aaaaaaaa(aaaaaaaa) {}",
+ Style);
+ Style.PackConstructorInitializers = FormatStyle::PCIS_NextLineOnly;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : aaaaaaaa(aaaaaaaa)\n"
+ " , aaaaaaaa(aaaaaaaa)\n"
+ " , aaaaaaaa(aaaaaaaa) {}",
+ Style);
+}
+
+TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
+ Style.ConstructorInitializerIndentWidth = 4;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a{a}\n"
+ " , b{b} {}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a{a}\n"
+ "#if CONDITION\n"
+ " , b{b}\n"
+ "#endif\n"
+ "{\n}",
+ Style);
+ Style.ConstructorInitializerIndentWidth = 2;
+ verifyFormat("SomeClass::Constructor()\n"
+ "#if CONDITION\n"
+ " : a{a}\n"
+ "#endif\n"
+ " , b{b}\n"
+ " , c{c} {\n}",
+ Style);
+ Style.ConstructorInitializerIndentWidth = 0;
+ verifyFormat("SomeClass::Constructor()\n"
+ ": a{a}\n"
+ "#ifdef CONDITION\n"
+ ", b{b}\n"
+ "#else\n"
+ ", c{c}\n"
+ "#endif\n"
+ ", d{d} {\n}",
+ Style);
+ Style.ConstructorInitializerIndentWidth = 4;
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a{a}\n"
+ "#if WINDOWS\n"
+ "#if DEBUG\n"
+ " , b{0}\n"
+ "#else\n"
+ " , b{1}\n"
+ "#endif\n"
+ "#else\n"
+ "#if DEBUG\n"
+ " , b{2}\n"
+ "#else\n"
+ " , b{3}\n"
+ "#endif\n"
+ "#endif\n"
+ "{\n}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a{a}\n"
+ "#if WINDOWS\n"
+ " , b{0}\n"
+ "#if DEBUG\n"
+ " , c{0}\n"
+ "#else\n"
+ " , c{1}\n"
+ "#endif\n"
+ "#else\n"
+ "#if DEBUG\n"
+ " , c{2}\n"
+ "#else\n"
+ " , c{3}\n"
+ "#endif\n"
+ " , b{1}\n"
+ "#endif\n"
+ "{\n}",
+ Style);
+}
+
+TEST_F(FormatTest, Destructors) {
+ verifyFormat("void F(int &i) { i.~int(); }");
+ verifyFormat("void F(int &i) { i->~int(); }");
+}
+
+TEST_F(FormatTest, FormatsWithWebKitStyle) {
+ FormatStyle Style = getWebKitStyle();
+
+ // Don't indent in outer namespaces.
+ verifyFormat("namespace outer {\n"
+ "int i;\n"
+ "namespace inner {\n"
+ " int i;\n"
+ "} // namespace inner\n"
+ "} // namespace outer\n"
+ "namespace other_outer {\n"
+ "int i;\n"
+ "}",
+ Style);
+
+ // Don't indent case labels.
+ verifyFormat("switch (variable) {\n"
+ "case 1:\n"
+ "case 2:\n"
+ " doSomething();\n"
+ " break;\n"
+ "default:\n"
+ " ++variable;\n"
+ "}",
+ Style);
+
+ // Wrap before binary operators.
+ verifyFormat(
+ "void f()\n"
+ "{\n"
+ " if (aaaaaaaaaaaaaaaa\n"
+ " && bbbbbbbbbbbbbbbbbbbbbbbb\n"
+ " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
+ " return;\n"
+ "}",
+ "void f() {\n"
+ "if (aaaaaaaaaaaaaaaa\n"
+ "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
+ "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
+ "return;\n"
+ "}",
+ Style);
+
+ // Allow functions on a single line.
+ verifyFormat("void f() { return; }", Style);
+
+ // Allow empty blocks on a single line and insert a space in empty blocks.
+ verifyFormat("void f() { }", "void f() {}", Style);
+ verifyFormat("while (true) { }", "while (true) {}", Style);
+ // However, don't merge non-empty short loops.
+ verifyFormat("while (true) {\n"
+ " continue;\n"
+ "}",
+ "while (true) { continue; }", Style);
+
+ // Constructor initializers are formatted one per line with the "," on the
+ // new line.
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
+ " aaaaaaaaaaaaaa)\n"
+ " , aaaaaaaaaaaaaaaaaaaaaaa()\n"
+ "{\n"
+ "}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ "{\n"
+ "}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ "{\n"
+ "}",
+ "SomeClass::Constructor():a(a){}", Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ " , b(b)\n"
+ " , c(c)\n"
+ "{\n"
+ "}",
+ Style);
+ verifyFormat("SomeClass::Constructor()\n"
+ " : a(a)\n"
+ "{\n"
+ " foo();\n"
+ " bar();\n"
+ "}",
+ Style);
+
+ // Access specifiers should be aligned left.
+ verifyFormat("class C {\n"
+ "public:\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ // Do not align comments.
+ verifyFormat("int a; // Do not\n"
+ "double b; // align comments.",
+ Style);
+
+ // Do not align operands.
+ verifyFormat("ASSERT(aaaa\n"
+ " || bbbb);",
+ "ASSERT ( aaaa\n||bbbb);", Style);
+
+ // Accept input's line breaks.
+ verifyFormat("if (aaaaaaaaaaaaaaa\n"
+ " || bbbbbbbbbbbbbbb) {\n"
+ " i++;\n"
+ "}",
+ "if (aaaaaaaaaaaaaaa\n"
+ "|| bbbbbbbbbbbbbbb) { i++; }",
+ Style);
+ verifyFormat("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
+ " i++;\n"
+ "}",
+ "if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style);
+
+ // Don't automatically break all macro definitions (llvm.org/PR17842).
+ verifyFormat("#define aNumber 10", Style);
+ // However, generally keep the line breaks that the user authored.
+ verifyFormat("#define aNumber \\\n"
+ " 10",
+ "#define aNumber \\\n"
+ " 10",
+ Style);
+
+ // Keep empty and one-element array literals on a single line.
+ verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
+ " copyItems:YES];",
+ "NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
+ "copyItems:YES];",
+ Style);
+ verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
+ " copyItems:YES];",
+ "NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
+ " copyItems:YES];",
+ Style);
+ // FIXME: This does not seem right, there should be more indentation before
+ // the array literal's entries. Nested blocks have the same problem.
+ verifyFormat("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
+ " @\"a\",\n"
+ " @\"a\"\n"
+ "]\n"
+ " copyItems:YES];",
+ "NSArray* a = [[NSArray alloc] initWithArray:@[\n"
+ " @\"a\",\n"
+ " @\"a\"\n"
+ " ]\n"
+ " copyItems:YES];",
+ Style);
+ verifyFormat(
+ "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
+ " copyItems:YES];",
+ "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
+ " copyItems:YES];",
+ Style);
+
+ verifyFormat("[self.a b:c c:d];", Style);
+ verifyFormat("[self.a b:c\n"
+ " c:d];",
+ "[self.a b:c\n"
+ "c:d];",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsLambdas) {
+ verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();");
+ verifyFormat(
+ "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();");
+ verifyFormat("int c = [&] { [=] { return b++; }(); }();");
+ verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();");
+ verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();");
+ verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}");
+ verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}");
+ verifyFormat("auto c = [a = [b = 42] {}] {};");
+ verifyFormat("auto c = [a = &i + 10, b = [] {}] {};");
+ verifyFormat("int x = f(*+[] {});");
+ verifyFormat("void f() {\n"
+ " other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " other(x.begin(), //\n"
+ " x.end(), //\n"
+ " [&](int, int) { return 1; });\n"
+ "}");
+ verifyFormat("void f() {\n"
+ " other.other.other.other.other(\n"
+ " x.begin(), x.end(),\n"
+ " [something, rather](int, int, int, int, int, int, int) { "
+ "return 1; });\n"
+ "}");
+ verifyFormat(
+ "void f() {\n"
+ " other.other.other.other.other(\n"
+ " x.begin(), x.end(),\n"
+ " [something, rather](int, int, int, int, int, int, int) {\n"
+ " //\n"
+ " });\n"
+ "}");
+ verifyFormat("SomeFunction([]() { // A cool function...\n"
+ " return 43;\n"
+ "});");
+ verifyFormat("SomeFunction([]() {\n"
+ "#define A a\n"
+ " return 43;\n"
+ "});",
+ "SomeFunction([](){\n"
+ "#define A a\n"
+ "return 43;\n"
+ "});");
+ verifyFormat("void f() {\n"
+ " SomeFunction([](decltype(x), A *a) {});\n"
+ " SomeFunction([](typeof(x), A *a) {});\n"
+ " SomeFunction([](_Atomic(x), A *a) {});\n"
+ " SomeFunction([](__underlying_type(x), A *a) {});\n"
+ "}");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " [](const aaaaaaaaaa &a) { return a; });");
+ verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
+ " SomeOtherFunctioooooooooooooooooooooooooon();\n"
+ "});");
+ verifyFormat("Constructor()\n"
+ " : Field([] { // comment\n"
+ " int i;\n"
+ " }) {}");
+ verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
+ " return some_parameter.size();\n"
+ "};");
+ verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
+ " [](const string &s) { return s; };");
+ verifyFormat("int i = aaaaaa ? 1 //\n"
+ " : [] {\n"
+ " return 2; //\n"
+ " }();");
+ verifyFormat("llvm::errs() << \"number of twos is \"\n"
+ " << std::count_if(v.begin(), v.end(), [](int x) {\n"
+ " return x == 2; // force break\n"
+ " });");
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " [=](int iiiiiiiiiiii) {\n"
+ " return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa;\n"
+ " });",
+ getLLVMStyleWithColumns(60));
+
+ verifyFormat("SomeFunction({[&] {\n"
+ " // comment\n"
+ " },\n"
+ " [&] {\n"
+ " // comment\n"
+ " }});");
+ verifyFormat("SomeFunction({[&] {\n"
+ " // comment\n"
+ "}});");
+ verifyFormat(
+ "virtual aaaaaaaaaaaaaaaa(\n"
+ " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
+ " aaaaa aaaaaaaaa);");
+
+ // Lambdas with return types.
+ verifyFormat("int c = []() -> int { return 2; }();");
+ verifyFormat("int c = []() -> int * { return 2; }();");
+ verifyFormat("int c = []() -> vector<int> { return {2}; }();");
+ verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
+ verifyFormat("foo([]() noexcept -> int {});");
+ verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
+ verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
+ verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
+ verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
+ verifyFormat("[a, a]() -> a<1> {};");
+ verifyFormat("[]() -> foo<5 + 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 - 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 / 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 * 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 % 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 << 2> { return {}; };");
+ verifyFormat("[]() -> foo<!5> { return {}; };");
+ verifyFormat("[]() -> foo<~5> { return {}; };");
+ verifyFormat("[]() -> foo<5 | 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 || 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 & 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 && 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 == 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 != 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
+ verifyFormat("[]() -> foo<5 < 2> { return {}; };");
+ verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<!5> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<~5> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("namespace bar {\n"
+ "// broken:\n"
+ "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
+ "} // namespace bar");
+ verifyFormat("[]() -> a<1> {};");
+ verifyFormat("[]() -> a<1> { ; };");
+ verifyFormat("[]() -> a<1> { ; }();");
+ verifyFormat("[a, a]() -> a<true> {};");
+ verifyFormat("[]() -> a<true> {};");
+ verifyFormat("[]() -> a<true> { ; };");
+ verifyFormat("[]() -> a<true> { ; }();");
+ verifyFormat("[a, a]() -> a<false> {};");
+ verifyFormat("[]() -> a<false> {};");
+ verifyFormat("[]() -> a<false> { ; };");
+ verifyFormat("[]() -> a<false> { ; }();");
+ verifyFormat("auto foo{[]() -> foo<false> { ; }};");
+ verifyFormat("namespace bar {\n"
+ "auto foo{[]() -> foo<false> { ; }};\n"
+ "} // namespace bar");
+ verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
+ " int j) -> int {\n"
+ " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
+ "};");
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaa(\n"
+ " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
+ " return aaaaaaaaaaaaaaaaa;\n"
+ " });",
+ getLLVMStyleWithColumns(70));
+ verifyFormat("[]() //\n"
+ " -> int {\n"
+ " return 1; //\n"
+ "};");
+ verifyFormat("[]() -> Void<T...> {};");
+ verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
+ verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
+ verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
+ verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
+ verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
+ verifyFormat("foo([&](u32 bar) __attribute__((always_inline)) -> void {});");
+ verifyFormat("return int{[x = x]() { return x; }()};");
+
+ // Lambdas with explicit template argument lists.
+ verifyFormat(
+ "auto L = []<template <typename> class T, class U>(T<U> &&a) {};");
+ verifyFormat("auto L = []<class T>(T) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []<class... T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []<typename... T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []<int... T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+ verifyFormat("auto L = []<Foo... T>(T...) {\n"
+ " {\n"
+ " f();\n"
+ " g();\n"
+ " }\n"
+ "};");
+
+ // Lambdas that fit on a single line within an argument list are not forced
+ // onto new lines.
+ verifyFormat("SomeFunction([] {});");
+ verifyFormat("SomeFunction(0, [] {});");
+ verifyFormat("SomeFunction([] {}, 0);");
+ verifyFormat("SomeFunction(0, [] {}, 0);");
+ verifyFormat("SomeFunction([] { return 0; }, 0);");
+ verifyFormat("SomeFunction(a, [] { return 0; }, b);");
+ verifyFormat("SomeFunction([] { return 0; }, [] { return 0; });");
+ verifyFormat("SomeFunction([] { return 0; }, [] { return 0; }, b);");
+ verifyFormat("auto loooooooooooooooooooooooooooong =\n"
+ " SomeFunction([] { return 0; }, [] { return 0; }, b);");
+ // Exceeded column limit. We need to break.
+ verifyFormat("auto loooooooooooooooooooooooooooongName = SomeFunction(\n"
+ " [] { return anotherLooooooooooonoooooooongName; }, [] { "
+ "return 0; }, b);");
+
+ // Multiple multi-line lambdas in the same parentheses change indentation
+ // rules. These lambdas are always forced to start on new lines.
+ verifyFormat("SomeFunction(\n"
+ " []() {\n"
+ " //\n"
+ " },\n"
+ " []() {\n"
+ " //\n"
+ " });");
+
+ // A multi-line lambda passed as arg0 is always pushed to the next line.
+ verifyFormat("SomeFunction(\n"
+ " [this] {\n"
+ " //\n"
+ " },\n"
+ " 1);");
+
+ // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
+ // the arg0 case above.
+ auto Style = getGoogleStyle();
+ Style.BinPackArguments = false;
+ verifyFormat("SomeFunction(\n"
+ " a,\n"
+ " [this] {\n"
+ " //\n"
+ " },\n"
+ " b);",
+ Style);
+ verifyFormat("SomeFunction(\n"
+ " a,\n"
+ " [this] {\n"
+ " //\n"
+ " },\n"
+ " b);");
+
+ // A lambda with a very long line forces arg0 to be pushed out irrespective of
+ // the BinPackArguments value (as long as the code is wide enough).
+ verifyFormat(
+ "something->SomeFunction(\n"
+ " a,\n"
+ " [this] {\n"
+ " "
+ "D0000000000000000000000000000000000000000000000000000000000001();\n"
+ " },\n"
+ " b);");
+
+ // A multi-line lambda is pulled up as long as the introducer fits on the
+ // previous line and there are no further args.
+ verifyFormat("function(1, [this, that] {\n"
+ " //\n"
+ "});");
+ verifyFormat("function([this, that] {\n"
+ " //\n"
+ "});");
+ // FIXME: this format is not ideal and we should consider forcing the first
+ // arg onto its own line.
+ verifyFormat("function(a, b, c, //\n"
+ " d, [this, that] {\n"
+ " //\n"
+ " });");
+
+ // Multiple lambdas are treated correctly even when there is a short arg0.
+ verifyFormat("SomeFunction(\n"
+ " 1,\n"
+ " [this] {\n"
+ " //\n"
+ " },\n"
+ " [this] {\n"
+ " //\n"
+ " },\n"
+ " 1);");
+
+ // More complex introducers.
+ verifyFormat("return [i, args...] {};");
+
+ // Not lambdas.
+ verifyFormat("constexpr char hello[]{\"hello\"};");
+ verifyFormat("double &operator[](int i) { return 0; }\n"
+ "int i;");
+ verifyFormat("std::unique_ptr<int[]> foo() {}");
+ verifyFormat("int i = a[a][a]->f();");
+ verifyFormat("int i = (*b)[a]->f();");
+
+ // Other corner cases.
+ verifyFormat("void f() {\n"
+ " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
+ " );\n"
+ "}");
+ verifyFormat("auto k = *[](int *j) { return j; }(&i);");
+
+ // Lambdas created through weird macros.
+ verifyFormat("void f() {\n"
+ " MACRO((const AA &a) { return 1; });\n"
+ " MACRO((AA &a) { return 1; });\n"
+ "}");
+
+ verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
+ " doo_dah();\n"
+ " doo_dah();\n"
+ " })) {\n"
+ "}");
+ verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
+ " doo_dah();\n"
+ " doo_dah();\n"
+ " })) {\n"
+ "}");
+ verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
+ " doo_dah();\n"
+ " doo_dah();\n"
+ " })) {\n"
+ "}");
+ verifyFormat("auto lambda = []() {\n"
+ " int a = 2\n"
+ "#if A\n"
+ " + 2\n"
+ "#endif\n"
+ " ;\n"
+ "};");
+
+ // Lambdas with complex multiline introducers.
+ verifyFormat(
+ "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
+ " -> ::std::unordered_set<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
+ " //\n"
+ " });");
+
+ FormatStyle LLVMStyle = getLLVMStyleWithColumns(60);
+ verifyFormat("very_long_function_name_yes_it_is_really_long(\n"
+ " [](auto n) noexcept [[back_attr]]\n"
+ " -> std::unordered_map<very_long_type_name_A,\n"
+ " very_long_type_name_B> {\n"
+ " really_do_something();\n"
+ " });",
+ LLVMStyle);
+ verifyFormat("very_long_function_name_yes_it_is_really_long(\n"
+ " [](auto n) constexpr\n"
+ " -> std::unordered_map<very_long_type_name_A,\n"
+ " very_long_type_name_B> {\n"
+ " really_do_something();\n"
+ " });",
+ LLVMStyle);
+
+ FormatStyle DoNotMerge = getLLVMStyle();
+ DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ verifyFormat("auto c = []() {\n"
+ " return b;\n"
+ "};",
+ "auto c = []() { return b; };", DoNotMerge);
+ verifyFormat("auto c = []() {\n"
+ "};",
+ " auto c = []() {};", DoNotMerge);
+
+ FormatStyle MergeEmptyOnly = getLLVMStyle();
+ MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
+ verifyFormat("auto c = []() {\n"
+ " return b;\n"
+ "};",
+ "auto c = []() {\n"
+ " return b;\n"
+ " };",
+ MergeEmptyOnly);
+ verifyFormat("auto c = []() {};",
+ "auto c = []() {\n"
+ "};",
+ MergeEmptyOnly);
+
+ FormatStyle MergeInline = getLLVMStyle();
+ MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
+ verifyFormat("auto c = []() {\n"
+ " return b;\n"
+ "};",
+ "auto c = []() { return b; };", MergeInline);
+ verifyFormat("function([]() { return b; })", MergeInline);
+ verifyFormat("function([]() { return b; }, a)", MergeInline);
+ verifyFormat("function(a, []() { return b; })", MergeInline);
+ verifyFormat("auto guard = foo{[&] { exit_status = true; }};", MergeInline);
+
+ // Check option "BraceWrapping.BeforeLambdaBody" and different state of
+ // AllowShortLambdasOnASingleLine
+ FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
+ LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
+ LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_None;
+ verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
+ " []()\n"
+ " {\n"
+ " return 17;\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
+ " []()\n"
+ " {\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto fct_SLS_None = []()\n"
+ "{\n"
+ " return 17;\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_None(\n"
+ " []()\n"
+ " {\n"
+ " return Call(\n"
+ " []()\n"
+ " {\n"
+ " return 17;\n"
+ " });\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("void Fct() {\n"
+ " return {[]()\n"
+ " {\n"
+ " return 17;\n"
+ " }};\n"
+ "}",
+ LLVMWithBeforeLambdaBody);
+
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_Empty;
+ verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
+ " []()\n"
+ " {\n"
+ " return 17;\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
+ "ongFunctionName_SLS_Empty(\n"
+ " []() {});",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
+ " []()\n"
+ " {\n"
+ " return 17;\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto fct_SLS_Empty = []()\n"
+ "{\n"
+ " return 17;\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
+ " []()\n"
+ " {\n"
+ " return Call([]() {});\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
+ " []()\n"
+ " {\n"
+ " return Call([]() {});\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_Empty(\n"
+ " []()\n"
+ " {\n"
+ " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
+ " AndShouldNotBeConsiderAsInline,\n"
+ " LambdaBodyMustBeBreak);\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_Inline;
+ verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto fct_SLS_Inline = []()\n"
+ "{\n"
+ " return 17;\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
+ "17; }); });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_Inline(\n"
+ " []()\n"
+ " {\n"
+ " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
+ " AndShouldNotBeConsiderAsInline,\n"
+ " LambdaBodyMustBeBreak);\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithMultipleParams_SLS_Inline("
+ "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
+ " []() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_All;
+ verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto fct_SLS_All = []() { return 17; };",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneParam_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " // A cool function...\n"
+ " return 43;\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithMultipleParams_SLS_All("
+ "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
+ " []() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
+ " AndShouldNotBeConsiderAsInline,\n"
+ " LambdaBodyMustBeBreak);\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "auto fct_SLS_All = []()\n"
+ "{\n"
+ " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
+ " AndShouldNotBeConsiderAsInline,\n"
+ " LambdaBodyMustBeBreak);\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+ LLVMWithBeforeLambdaBody.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
+ " FirstParam,\n"
+ " SecondParam,\n"
+ " ThirdParam,\n"
+ " FourthParam);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
+ " []() { return "
+ "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
+ " FirstParam,\n"
+ " SecondParam,\n"
+ " ThirdParam,\n"
+ " FourthParam);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
+ " SecondParam,\n"
+ " ThirdParam,\n"
+ " FourthParam,\n"
+ " []() { return SomeValueNotSoLong; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " return "
+ "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
+ "eConsiderAsInline;\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithLongLineInLambda_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
+ " AndShouldNotBeConsiderAsInline,\n"
+ " LambdaBodyMustBeBreak);\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithTwoParams_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " // A cool function...\n"
+ " return 43;\n"
+ " },\n"
+ " 87);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithTwoParams_SLS_All(\n"
+ " 87, []() { return LongLineThatWillForceBothParamsToNewLine(); });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "FctWithTwoParams_SLS_All(\n"
+ " 87,\n"
+ " []()\n"
+ " {\n"
+ " return "
+ "LongLineThatWillForceTheLambdaBodyToBeBrokenIntoMultipleLines();\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
+ "}); }, x);",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " // A cool function...\n"
+ " return Call([]() { return 17; });\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("TwoNestedLambdas_SLS_All(\n"
+ " []()\n"
+ " {\n"
+ " return Call(\n"
+ " []()\n"
+ " {\n"
+ " // A cool function...\n"
+ " return 17;\n"
+ " });\n"
+ " });",
+ LLVMWithBeforeLambdaBody);
+
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_None;
+
+ verifyFormat("auto select = [this]() -> const Library::Object *\n"
+ "{\n"
+ " return MyAssignment::SelectFromList(this);\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+
+ verifyFormat("auto select = [this]() -> const Library::Object &\n"
+ "{\n"
+ " return MyAssignment::SelectFromList(this);\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+
+ verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
+ "{\n"
+ " return MyAssignment::SelectFromList(this);\n"
+ "};",
+ LLVMWithBeforeLambdaBody);
+
+ verifyFormat("namespace test {\n"
+ "class Test {\n"
+ "public:\n"
+ " Test() = default;\n"
+ "};\n"
+ "} // namespace test",
+ LLVMWithBeforeLambdaBody);
+
+ // Lambdas with different indentation styles.
+ Style = getLLVMStyleWithColumns(60);
+ verifyFormat("Result doSomething(Promise promise) {\n"
+ " return promise.then(\n"
+ " [this, obj = std::move(s)](int bar) mutable {\n"
+ " return someObject.startAsyncAction().then(\n"
+ " [this, &obj](Result result) mutable {\n"
+ " result.processMore();\n"
+ " });\n"
+ " });\n"
+ "}",
+ Style);
+ Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
+ verifyFormat("Result doSomething(Promise promise) {\n"
+ " return promise.then(\n"
+ " [this, obj = std::move(s)](int bar) mutable {\n"
+ " return obj.startAsyncAction().then(\n"
+ " [this, &obj](Result result) mutable {\n"
+ " result.processMore();\n"
+ " });\n"
+ " });\n"
+ "}",
+ Style);
+ verifyFormat("Result doSomething(Promise promise) {\n"
+ " return promise.then([this, obj = std::move(s)] {\n"
+ " return obj.startAsyncAction().then(\n"
+ " [this, &obj](Result result) mutable {\n"
+ " result.processMore();\n"
+ " });\n"
+ " });\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " ([]() -> auto {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " }).foo();\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " []() -> auto {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " }\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " std::sort(v.begin(), v.end(),\n"
+ " [](const auto &foo, const auto &bar) {\n"
+ " return foo.baz < bar.baz;\n"
+ " });\n"
+ "};",
+ Style);
+ verifyFormat("void test() {\n"
+ " (\n"
+ " []() -> auto {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " }, foo, bar)\n"
+ " .foo();\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " ([]() -> auto {\n"
+ " int b = 32;\n"
+ " return 3;\n"
+ " })\n"
+ " .foo()\n"
+ " .bar();\n"
+ "}",
+ Style);
+ verifyFormat("#define A \\\n"
+ " [] { \\\n"
+ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
+ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
+ " }",
+ Style);
+ verifyFormat("#define SORT(v) \\\n"
+ " std::sort(v.begin(), v.end(), \\\n"
+ " [](const auto &foo, const auto &bar) { \\\n"
+ " return foo.baz < bar.baz; \\\n"
+ " });",
+ Style);
+ verifyFormat("void foo() {\n"
+ " aFunction(1, b(c(foo, bar, baz, [](d) {\n"
+ " auto f = e(d);\n"
+ " return f;\n"
+ " })));\n"
+ "}",
+ Style);
+ verifyFormat("void foo() {\n"
+ " aFunction(1, b(c(foo, Bar{}, baz, [](d) -> Foo {\n"
+ " auto f = e(foo, [&] {\n"
+ " auto g = h();\n"
+ " return g;\n"
+ " }, qux, [&] -> Bar {\n"
+ " auto i = j();\n"
+ " return i;\n"
+ " });\n"
+ " return f;\n"
+ " })));\n"
+ "}",
+ Style);
+ verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
+ " AnotherLongClassName baz)\n"
+ " : baz{baz}, func{[&] {\n"
+ " auto qux = bar;\n"
+ " return aFunkyFunctionCall(qux);\n"
+ " }} {}",
+ Style);
+ verifyFormat("void foo() {\n"
+ " class Foo {\n"
+ " public:\n"
+ " Foo()\n"
+ " : qux{[](int quux) {\n"
+ " auto tmp = quux;\n"
+ " return tmp;\n"
+ " }} {}\n"
+ "\n"
+ " private:\n"
+ " std::function<void(int quux)> qux;\n"
+ " };\n"
+ "}",
+ Style);
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
+ verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
+ " AnotherLongClassName baz) :\n"
+ " baz{baz}, func{[&] {\n"
+ " auto qux = bar;\n"
+ " return aFunkyFunctionCall(qux);\n"
+ " }} {}",
+ Style);
+ Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
+ verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
+ " AnotherLongClassName baz) :\n"
+ " baz{baz},\n"
+ " func{[&] {\n"
+ " auto qux = bar;\n"
+ " return aFunkyFunctionCall(qux);\n"
+ " }} {}",
+ Style);
+ Style.BreakAfterOpenBracketFunction = true;
+ // FIXME: The following test should pass, but fails at the time of writing.
+#if 0
+ // As long as all the non-lambda arguments fit on a single line, AlwaysBreak
+ // doesn't force an initial line break, even if lambdas span multiple lines.
+ verifyFormat("void foo() {\n"
+ " aFunction(\n"
+ " [](d) -> Foo {\n"
+ " auto f = e(d);\n"
+ " return f;\n"
+ " }, foo, Bar{}, [] {\n"
+ " auto g = h();\n"
+ " return g;\n"
+ " }, baz);\n"
+ "}",
+ Style);
+#endif
+ // A long non-lambda argument forces arguments to span multiple lines and thus
+ // forces an initial line break when using AlwaysBreak.
+ verifyFormat("void foo() {\n"
+ " aFunction(\n"
+ " 1,\n"
+ " [](d) -> Foo {\n"
+ " auto f = e(d);\n"
+ " return f;\n"
+ " }, foo, Bar{},\n"
+ " [] {\n"
+ " auto g = h();\n"
+ " return g;\n"
+ " }, bazzzzz,\n"
+ " quuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux);\n"
+ "}",
+ Style);
+ Style.BinPackArguments = false;
+ verifyFormat("void foo() {\n"
+ " aFunction(\n"
+ " 1,\n"
+ " [](d) -> Foo {\n"
+ " auto f = e(d);\n"
+ " return f;\n"
+ " },\n"
+ " foo,\n"
+ " Bar{},\n"
+ " [] {\n"
+ " auto g = h();\n"
+ " return g;\n"
+ " },\n"
+ " bazzzzz,\n"
+ " quuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux);\n"
+ "}",
+ Style);
+ Style.BinPackArguments = true;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeLambdaBody = true;
+ verifyFormat("void foo() {\n"
+ " aFunction(\n"
+ " 1, b(c(foo, Bar{}, baz, [](d) -> Foo\n"
+ " {\n"
+ " auto f = e(\n"
+ " [&]\n"
+ " {\n"
+ " auto g = h();\n"
+ " return g;\n"
+ " }, qux, [&] -> Bar\n"
+ " {\n"
+ " auto i = j();\n"
+ " return i;\n"
+ " });\n"
+ " return f;\n"
+ " })));\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, LambdaWithLineComments) {
+ FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
+ LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
+ LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
+ LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
+ FormatStyle::SLS_All;
+
+ verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
+ verifyFormat("auto k = []() // comment\n"
+ "{ return; }",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto k = []() /* comment */ { return; }",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("auto k = []() // X\n"
+ "{ return; }",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat(
+ "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
+ "{ return; }",
+ LLVMWithBeforeLambdaBody);
+
+ LLVMWithBeforeLambdaBody.ColumnLimit = 0;
+
+ verifyFormat("foo([]()\n"
+ " {\n"
+ " bar(); //\n"
+ " return 1; // comment\n"
+ " }());",
+ "foo([]() {\n"
+ " bar(); //\n"
+ " return 1; // comment\n"
+ "}());",
+ LLVMWithBeforeLambdaBody);
+ verifyFormat("foo(\n"
+ " 1, MACRO {\n"
+ " baz();\n"
+ " bar(); // comment\n"
+ " },\n"
+ " []() {});",
+ "foo(\n"
+ " 1, MACRO { baz(); bar(); // comment\n"
+ " }, []() {}\n"
+ ");",
+ LLVMWithBeforeLambdaBody);
+}
+
+TEST_F(FormatTest, EmptyLinesInLambdas) {
+ verifyFormat("auto lambda = []() {\n"
+ " x(); //\n"
+ "};",
+ "auto lambda = []() {\n"
+ "\n"
+ " x(); //\n"
+ "\n"
+ "};");
+}
+
+TEST_F(FormatTest, LambdaBracesInGNU) {
+ auto Style = getGNUStyle();
+ EXPECT_EQ(Style.LambdaBodyIndentation, FormatStyle::LBI_Signature);
+
+ constexpr StringRef Code("auto x = [&] ()\n"
+ " {\n"
+ " for (int i = 0; i < y; ++i)\n"
+ " return 97;\n"
+ " };");
+ verifyFormat(Code, Style);
+
+ Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
+ verifyFormat(Code, Style);
+ verifyFormat("for_each_thread ([] (thread_info *thread)\n"
+ " {\n"
+ " /* Lambda body. */\n"
+ " });",
+ "for_each_thread([](thread_info *thread) {\n"
+ " /* Lambda body. */\n"
+ "});",
+ Style);
+ verifyFormat("iterate_over_lwps (scope_ptid, [=] (struct lwp_info *info)\n"
+ " {\n"
+ " /* Lambda body. */\n"
+ " });",
+ "iterate_over_lwps(scope_ptid, [=](struct lwp_info *info) {\n"
+ " /* Lambda body. */\n"
+ "});",
+ Style);
+}
+
+TEST_F(FormatTest, FormatsBlocks) {
+ FormatStyle ShortBlocks = getLLVMStyle();
+ ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ verifyFormat("int (^Block)(int, int);", ShortBlocks);
+ verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
+ verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
+ verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
+ verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
+ verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
+
+ verifyFormat("foo(^{ bar(); });", ShortBlocks);
+ verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
+ verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
+
+ verifyFormat("[operation setCompletionBlock:^{\n"
+ " [self onOperationDone];\n"
+ "}];");
+ verifyFormat("int i = {[operation setCompletionBlock:^{\n"
+ " [self onOperationDone];\n"
+ "}]};");
+ verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
+ " f();\n"
+ "}];");
+ verifyFormat("int a = [operation block:^int(int *i) {\n"
+ " return 1;\n"
+ "}];");
+ verifyFormat("[myObject doSomethingWith:arg1\n"
+ " aaa:^int(int *a) {\n"
+ " return 1;\n"
+ " }\n"
+ " bbb:f(a * bbbbbbbb)];");
+
+ verifyFormat("[operation setCompletionBlock:^{\n"
+ " [self.delegate newDataAvailable];\n"
+ "}];",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
+ " NSString *path = [self sessionFilePath];\n"
+ " if (path) {\n"
+ " // ...\n"
+ " }\n"
+ "});");
+ verifyFormat("[[SessionService sharedService]\n"
+ " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
+ " if (window) {\n"
+ " [self windowDidLoad:window];\n"
+ " } else {\n"
+ " [self errorLoadingWindow];\n"
+ " }\n"
+ " }];");
+ verifyFormat("void (^largeBlock)(void) = ^{\n"
+ " // ...\n"
+ "};",
+ getLLVMStyleWithColumns(40));
+ verifyFormat("[[SessionService sharedService]\n"
+ " loadWindowWithCompletionBlock: //\n"
+ " ^(SessionWindow *window) {\n"
+ " if (window) {\n"
+ " [self windowDidLoad:window];\n"
+ " } else {\n"
+ " [self errorLoadingWindow];\n"
+ " }\n"
+ " }];",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("[myObject doSomethingWith:arg1\n"
+ " firstBlock:^(Foo *a) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }\n"
+ " secondBlock:^(Bar *b) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }\n"
+ " thirdBlock:^Foo(Bar *b) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }];");
+ verifyFormat("[myObject doSomethingWith:arg1\n"
+ " firstBlock:-1\n"
+ " secondBlock:^(Bar *b) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }];");
+
+ verifyFormat("f(^{\n"
+ " @autoreleasepool {\n"
+ " if (a) {\n"
+ " g();\n"
+ " }\n"
+ " }\n"
+ "});");
+ verifyFormat("Block b = ^int *(A *a, B *b) {\n"
+ "};");
+ verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
+ "};");
+
+ FormatStyle FourIndent = getLLVMStyle();
+ FourIndent.ObjCBlockIndentWidth = 4;
+ verifyFormat("[operation setCompletionBlock:^{\n"
+ " [self onOperationDone];\n"
+ "}];",
+ FourIndent);
+}
+
+TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
+ FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
+
+ verifyFormat("[[SessionService sharedService] "
+ "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
+ " if (window) {\n"
+ " [self windowDidLoad:window];\n"
+ " } else {\n"
+ " [self errorLoadingWindow];\n"
+ " }\n"
+ "}];",
+ ZeroColumn);
+ verifyFormat("[[SessionService sharedService]\n"
+ " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
+ " if (window) {\n"
+ " [self windowDidLoad:window];\n"
+ " } else {\n"
+ " [self errorLoadingWindow];\n"
+ " }\n"
+ " }];",
+ "[[SessionService sharedService]\n"
+ "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
+ " if (window) {\n"
+ " [self windowDidLoad:window];\n"
+ " } else {\n"
+ " [self errorLoadingWindow];\n"
+ " }\n"
+ "}];",
+ ZeroColumn);
+ verifyFormat("[myObject doSomethingWith:arg1\n"
+ " firstBlock:^(Foo *a) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }\n"
+ " secondBlock:^(Bar *b) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }\n"
+ " thirdBlock:^Foo(Bar *b) {\n"
+ " // ...\n"
+ " int i;\n"
+ " }];",
+ ZeroColumn);
+ verifyFormat("f(^{\n"
+ " @autoreleasepool {\n"
+ " if (a) {\n"
+ " g();\n"
+ " }\n"
+ " }\n"
+ "});",
+ ZeroColumn);
+ verifyFormat("void (^largeBlock)(void) = ^{\n"
+ " // ...\n"
+ "};",
+ ZeroColumn);
+
+ ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ verifyFormat("void (^largeBlock)(void) = ^{ int i; };",
+ "void (^largeBlock)(void) = ^{ int i; };", ZeroColumn);
+ ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+ verifyFormat("void (^largeBlock)(void) = ^{\n"
+ " int i;\n"
+ "};",
+ "void (^largeBlock)(void) = ^{ int i; };", ZeroColumn);
+}
+
+TEST_F(FormatTest, SupportsCRLF) {
+ verifyFormat("int a;\r\n"
+ "int b;\r\n"
+ "int c;",
+ "int a;\r\n"
+ " int b;\r\n"
+ " int c;");
+ verifyFormat("int a;\r\n"
+ "int b;\r\n"
+ "int c;\r\n",
+ "int a;\r\n"
+ " int b;\n"
+ " int c;\r\n");
+ verifyFormat("int a;\n"
+ "int b;\n"
+ "int c;",
+ "int a;\r\n"
+ " int b;\n"
+ " int c;");
+ // FIXME: unstable test case
+ EXPECT_EQ("\"aaaaaaa \"\r\n"
+ "\"bbbbbbb\";\r\n",
+ format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
+ verifyFormat("#define A \\\r\n"
+ " b; \\\r\n"
+ " c; \\\r\n"
+ " d;",
+ "#define A \\\r\n"
+ " b; \\\r\n"
+ " c; d; ",
+ getGoogleStyle());
+
+ verifyNoChange("/*\r\n"
+ "multi line block comments\r\n"
+ "should not introduce\r\n"
+ "an extra carriage return\r\n"
+ "*/");
+ verifyFormat("/*\r\n"
+ "\r\n"
+ "*/",
+ "/*\r\n"
+ " \r\r\r\n"
+ "*/");
+
+ FormatStyle style = getLLVMStyle();
+
+ EXPECT_EQ(style.LineEnding, FormatStyle::LE_DeriveLF);
+ verifyFormat("union FooBarBazQux {\n"
+ " int foo;\n"
+ " int bar;\n"
+ " int baz;\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ "};",
+ style);
+ style.LineEnding = FormatStyle::LE_DeriveCRLF;
+ verifyFormat("union FooBarBazQux {\r\n"
+ " int foo;\r\n"
+ " int bar;\r\n"
+ " int baz;\r\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ "};",
+ style);
+
+ style.LineEnding = FormatStyle::LE_LF;
+ verifyFormat("union FooBarBazQux {\n"
+ " int foo;\n"
+ " int bar;\n"
+ " int baz;\n"
+ " int qux;\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ " int qux;\r\n"
+ "};",
+ style);
+ style.LineEnding = FormatStyle::LE_CRLF;
+ verifyFormat("union FooBarBazQux {\r\n"
+ " int foo;\r\n"
+ " int bar;\r\n"
+ " int baz;\r\n"
+ " int qux;\r\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ " int qux;\n"
+ "};",
+ style);
+
+ style.LineEnding = FormatStyle::LE_DeriveLF;
+ verifyFormat("union FooBarBazQux {\r\n"
+ " int foo;\r\n"
+ " int bar;\r\n"
+ " int baz;\r\n"
+ " int qux;\r\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ " int qux;\r\n"
+ "};",
+ style);
+ style.LineEnding = FormatStyle::LE_DeriveCRLF;
+ verifyFormat("union FooBarBazQux {\n"
+ " int foo;\n"
+ " int bar;\n"
+ " int baz;\n"
+ " int qux;\n"
+ "};",
+ "union FooBarBazQux {\r\n"
+ " int foo;\n"
+ " int bar;\r\n"
+ " int baz;\n"
+ " int qux;\n"
+ "};",
+ style);
+}
+
+TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
+ verifyFormat("MY_CLASS(C) {\n"
+ " int i;\n"
+ " int j;\n"
+ "};");
+}
+
+TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
+ FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
+ TwoIndent.ContinuationIndentWidth = 2;
+
+ verifyFormat("int i =\n"
+ " longFunction(\n"
+ " arg);",
+ "int i = longFunction(arg);", TwoIndent);
+
+ FormatStyle SixIndent = getLLVMStyleWithColumns(20);
+ SixIndent.ContinuationIndentWidth = 6;
+
+ verifyFormat("int i =\n"
+ " longFunction(\n"
+ " arg);",
+ "int i = longFunction(arg);", SixIndent);
+}
+
+TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("int Foo::getter(\n"
+ " //\n"
+ ") const {\n"
+ " return foo;\n"
+ "}",
+ Style);
+ verifyFormat("void Foo::setter(\n"
+ " //\n"
+ ") {\n"
+ " foo = 1;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, SpacesInAngles) {
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+
+ verifyFormat("vector< ::std::string > x1;", Spaces);
+ verifyFormat("Foo< int, Bar > x2;", Spaces);
+ verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
+
+ verifyFormat("static_cast< int >(arg);", Spaces);
+ verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
+ verifyFormat("f< int, float >();", Spaces);
+ verifyFormat("template <> g() {}", Spaces);
+ verifyFormat("template < std::vector< int > > f() {}", Spaces);
+ verifyFormat("std::function< void(int, int) > fct;", Spaces);
+ verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
+ Spaces);
+
+ Spaces.Standard = FormatStyle::LS_Cpp03;
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+ verifyFormat("A< A< int > >();", Spaces);
+
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
+ verifyFormat("A<A<int> >();", Spaces);
+
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
+ verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
+ Spaces);
+ verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
+ Spaces);
+
+ verifyFormat("A<A<int> >();", Spaces);
+ verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
+ verifyFormat("A< A< int > >();", Spaces);
+
+ Spaces.Standard = FormatStyle::LS_Cpp11;
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+ verifyFormat("A< A< int > >();", Spaces);
+
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
+ verifyFormat("vector<::std::string> x4;", Spaces);
+ verifyFormat("vector<int> x5;", Spaces);
+ verifyFormat("Foo<int, Bar> x6;", Spaces);
+ verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
+
+ verifyFormat("A<A<int>>();", Spaces);
+
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
+ verifyFormat("vector<::std::string> x4;", Spaces);
+ verifyFormat("vector< ::std::string > x4;", Spaces);
+ verifyFormat("vector<int> x5;", Spaces);
+ verifyFormat("vector< int > x5;", Spaces);
+ verifyFormat("Foo<int, Bar> x6;", Spaces);
+ verifyFormat("Foo< int, Bar > x6;", Spaces);
+ verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
+ verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
+
+ verifyFormat("A<A<int>>();", Spaces);
+ verifyFormat("A< A< int > >();", Spaces);
+ verifyFormat("A<A<int > >();", Spaces);
+ verifyFormat("A< A< int>>();", Spaces);
+
+ Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+ verifyFormat("// clang-format off\n"
+ "foo<<<1, 1>>>();\n"
+ "// clang-format on",
+ Spaces);
+ verifyFormat("// clang-format off\n"
+ "foo< < <1, 1> > >();\n"
+ "// clang-format on",
+ Spaces);
+}
+
+TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
+ FormatStyle Style = getLLVMStyle();
+ Style.SpaceAfterTemplateKeyword = false;
+ verifyFormat("template<int> void foo();", Style);
+}
+
+TEST_F(FormatTest, TripleAngleBrackets) {
+ verifyFormat("f<<<1, 1>>>();");
+ verifyFormat("f<<<1, 1, 1, s>>>();");
+ verifyFormat("f<<<a, b, c, d>>>();");
+ verifyFormat("f<<<1, 1>>>();", "f <<< 1, 1 >>> ();");
+ verifyFormat("f<param><<<1, 1>>>();");
+ verifyFormat("f<1><<<1, 1>>>();");
+ verifyFormat("f<param><<<1, 1>>>();", "f< param > <<< 1, 1 >>> ();");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ "aaaaaaaaaaa<<<\n 1, 1>>>();");
+ verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
+ " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
+}
+
+TEST_F(FormatTest, MergeLessLessAtEnd) {
+ verifyFormat("<<");
+ verifyFormat("< < <", "\\\n<<<");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ "aaallvm::outs() <<");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ "aaaallvm::outs()\n <<");
+}
+
+TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
+ std::string code = "#if A\n"
+ "#if B\n"
+ "a.\n"
+ "#endif\n"
+ " a = 1;\n"
+ "#else\n"
+ "#endif\n"
+ "#if C\n"
+ "#else\n"
+ "#endif\n";
+ verifyFormat(code);
+}
+
+TEST_F(FormatTest, HandleConflictMarkers) {
+ // Git/SVN conflict markers.
+ verifyFormat("int a;\n"
+ "void f() {\n"
+ " callme(some(parameter1,\n"
+ "<<<<<<< text by the vcs\n"
+ " parameter2),\n"
+ "||||||| text by the vcs\n"
+ " parameter2),\n"
+ " parameter3,\n"
+ "======= text by the vcs\n"
+ " parameter2, parameter3),\n"
+ ">>>>>>> text by the vcs\n"
+ " otherparameter);",
+ "int a;\n"
+ "void f() {\n"
+ " callme(some(parameter1,\n"
+ "<<<<<<< text by the vcs\n"
+ " parameter2),\n"
+ "||||||| text by the vcs\n"
+ " parameter2),\n"
+ " parameter3,\n"
+ "======= text by the vcs\n"
+ " parameter2,\n"
+ " parameter3),\n"
+ ">>>>>>> text by the vcs\n"
+ " otherparameter);");
+
+ // Perforce markers.
+ verifyFormat("void f() {\n"
+ " function(\n"
+ ">>>> text by the vcs\n"
+ " parameter,\n"
+ "==== text by the vcs\n"
+ " parameter,\n"
+ "==== text by the vcs\n"
+ " parameter,\n"
+ "<<<< text by the vcs\n"
+ " parameter);",
+ "void f() {\n"
+ " function(\n"
+ ">>>> text by the vcs\n"
+ " parameter,\n"
+ "==== text by the vcs\n"
+ " parameter,\n"
+ "==== text by the vcs\n"
+ " parameter,\n"
+ "<<<< text by the vcs\n"
+ " parameter);");
+
+ verifyNoChange("<<<<<<<\n"
+ "|||||||\n"
+ "=======\n"
+ ">>>>>>>");
+
+ verifyNoChange("<<<<<<<\n"
+ "|||||||\n"
+ "int i;\n"
+ "=======\n"
+ ">>>>>>>");
+
+ // FIXME: Handle parsing of macros around conflict markers correctly:
+ verifyFormat("#define Macro \\\n"
+ "<<<<<<<\n"
+ "Something \\\n"
+ "|||||||\n"
+ "Else \\\n"
+ "=======\n"
+ "Other \\\n"
+ ">>>>>>>\n"
+ " End int i;",
+ "#define Macro \\\n"
+ "<<<<<<<\n"
+ " Something \\\n"
+ "|||||||\n"
+ " Else \\\n"
+ "=======\n"
+ " Other \\\n"
+ ">>>>>>>\n"
+ " End\n"
+ "int i;");
+
+ verifyFormat(R"(====
+#ifdef A
+a
+#else
+b
+#endif
+)");
+}
+
+TEST_F(FormatTest, DisableRegions) {
+ verifyFormat("int i;\n"
+ "// clang-format off\n"
+ " int j;\n"
+ "// clang-format on\n"
+ "int k;",
+ " int i;\n"
+ " // clang-format off\n"
+ " int j;\n"
+ " // clang-format on\n"
+ " int k;");
+ verifyFormat("int i;\n"
+ "/* clang-format off */\n"
+ " int j;\n"
+ "/* clang-format on */\n"
+ "int k;",
+ " int i;\n"
+ " /* clang-format off */\n"
+ " int j;\n"
+ " /* clang-format on */\n"
+ " int k;");
+
+ // Don't reflow comments within disabled regions.
+ verifyFormat("// clang-format off\n"
+ "// long long long long long long line\n"
+ "/* clang-format on */\n"
+ "/* long long long\n"
+ " * long long long\n"
+ " * line */\n"
+ "int i;\n"
+ "/* clang-format off */\n"
+ "/* long long long long long long line */",
+ "// clang-format off\n"
+ "// long long long long long long line\n"
+ "/* clang-format on */\n"
+ "/* long long long long long long line */\n"
+ "int i;\n"
+ "/* clang-format off */\n"
+ "/* long long long long long long line */",
+ getLLVMStyleWithColumns(20));
+
+ verifyFormat("int *i;\n"
+ "// clang-format off:\n"
+ "int* j;\n"
+ "// clang-format on: 1\n"
+ "int *k;",
+ "int* i;\n"
+ "// clang-format off:\n"
+ "int* j;\n"
+ "// clang-format on: 1\n"
+ "int* k;");
+
+ verifyFormat("int *i;\n"
+ "// clang-format off:0\n"
+ "int* j;\n"
+ "// clang-format only\n"
+ "int* k;",
+ "int* i;\n"
+ "// clang-format off:0\n"
+ "int* j;\n"
+ "// clang-format only\n"
+ "int* k;");
+
+ verifyNoChange("// clang-format off\n"
+ "#if 0\n"
+ " #if SHOULD_STAY_INDENTED\n"
+ " #endif\n"
+ "#endif\n"
+ "// clang-format on");
+}
+
+TEST_F(FormatTest, OneLineFormatOffRegex) {
+ auto Style = getLLVMStyle();
+ Style.OneLineFormatOffRegex = "// format off$";
+
+ verifyFormat(" // format off\n"
+ " int i ;\n"
+ "int j;",
+ " // format off\n"
+ " int i ;\n"
+ " int j ;",
+ Style);
+ verifyFormat("// format off?\n"
+ "int i;",
+ " // format off?\n"
+ " int i ;",
+ Style);
+ verifyFormat("f(\"// format off\");", " f(\"// format off\") ;", Style);
+
+ verifyFormat("int i;\n"
+ " // format off\n"
+ " int j ;\n"
+ "int k;",
+ " int i ;\n"
+ " // format off\n"
+ " int j ;\n"
+ " int k ;",
+ Style);
+
+ verifyFormat(" // format off\n"
+ "\n"
+ "int i;",
+ " // format off\n"
+ " \n"
+ " int i ;",
+ Style);
+
+ verifyFormat("int i;\n"
+ " int j ; // format off\n"
+ "int k;",
+ " int i ;\n"
+ " int j ; // format off\n"
+ " int k ;",
+ Style);
+
+ verifyFormat("// clang-format off\n"
+ " int i ;\n"
+ " int j ; // format off\n"
+ " int k ;\n"
+ "// clang-format on\n"
+ "f();",
+ " // clang-format off\n"
+ " int i ;\n"
+ " int j ; // format off\n"
+ " int k ;\n"
+ " // clang-format on\n"
+ " f() ;",
+ Style);
+
+ Style.OneLineFormatOffRegex = "^/\\* format off \\*/";
+ verifyFormat("int i;\n"
+ " /* format off */ int j ;\n"
+ "int k;",
+ " int i ;\n"
+ " /* format off */ int j ;\n"
+ " int k ;",
+ Style);
+ verifyFormat("f(\"/* format off */\");", " f(\"/* format off */\") ;", Style);
+
+ Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
+ verifyFormat("#define A \\\n"
+ " do { \\\n"
+ " /* format off */\\\n"
+ " f() ; \\\n"
+ " g(); \\\n"
+ " } while (0)",
+ "# define A\\\n"
+ " do{ \\\n"
+ " /* format off */\\\n"
+ " f() ; \\\n"
+ " g() ;\\\n"
+ " } while (0 )",
+ Style);
+
+ Style.OneLineFormatOffRegex = "MACRO_TEST";
+ verifyNoChange(" MACRO_TEST1 ( ) ;\n"
+ " MACRO_TEST2( );",
+ Style);
+
+ Style.ColumnLimit = 50;
+ Style.OneLineFormatOffRegex = "^LogErrorPrint$";
+ verifyFormat(" myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
+ "myproject::MyLogErrorPrinter(myLogger,\n"
+ " \"Split me!\");",
+ " myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
+ " myproject::MyLogErrorPrinter(myLogger, \"Split me!\");",
+ Style);
+
+ Style.OneLineFormatOffRegex = "//(< clang-format off| NO_TRANSLATION)$";
+ verifyNoChange(
+ " int i ; //< clang-format off\n"
+ " msg = sprintf(\"Long string with placeholders.\"); // NO_TRANSLATION",
+ Style);
+}
+
+TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
+ format("? ) =");
+ verifyNoCrash("#define a\\\n /**/}");
+ verifyNoCrash(" tst %o5 ! are we doing the gray case?\n"
+ "LY52: ! [internal]");
+}
+
+TEST_F(FormatTest, FormatsTableGenCode) {
+ FormatStyle Style = getLLVMStyle();
+ Style.Language = FormatStyle::LK_TableGen;
+ verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
+}
+
+TEST_F(FormatTest, ArrayOfTemplates) {
+ verifyFormat("auto a = new unique_ptr<int>[10];",
+ "auto a = new unique_ptr<int > [ 10];");
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInSquareBrackets = true;
+ verifyFormat("auto a = new unique_ptr<int>[ 10 ];",
+ "auto a = new unique_ptr<int > [10];", Spaces);
+}
+
+TEST_F(FormatTest, ArrayAsTemplateType) {
+ verifyFormat("auto a = unique_ptr<Foo<Bar>[10]>;",
+ "auto a = unique_ptr < Foo < Bar>[ 10]> ;");
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInSquareBrackets = true;
+ verifyFormat("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
+ "auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces);
+}
+
+TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
+
+TEST_F(FormatTest, FormatSortsUsingDeclarations) {
+ verifyFormat("using std::cin;\n"
+ "using std::cout;",
+ "using std::cout;\n"
+ "using std::cin;",
+ getGoogleStyle());
+}
+
+TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
+ FormatStyle Style = getLLVMStyle();
+ Style.Standard = FormatStyle::LS_Cpp03;
+ // cpp03 recognize this string as identifier u8 and literal character 'a'
+ verifyFormat("auto c = u8 'a';", "auto c = u8'a';", Style);
+}
+
+TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
+ // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
+ // all modes, including C++11, C++14 and C++17
+ verifyFormat("auto c = u8'a';");
+}
+
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+ verifyGoogleFormat("<!-- ;> -->");
+ verifyNoChange(" <!-- >; -->", getGoogleStyle());
+}
+
+TEST_F(FormatTest, StructuredBindings) {
+ // Structured bindings is a C++17 feature.
+ // all modes, including C++11, C++14 and C++17
+ verifyFormat("auto [a, b] = f();");
+ verifyFormat("auto [a, b] = f();", "auto[a, b] = f();");
+ verifyFormat("const auto [a, b] = f();", "const auto[a, b] = f();");
+ verifyFormat("auto const [a, b] = f();", "auto const[a, b] = f();");
+ verifyFormat("auto const volatile [a, b] = f();",
+ "auto const volatile[a, b] = f();");
+ verifyFormat("auto [a, b, c] = f();", "auto [ a , b,c ] = f();");
+ verifyFormat("auto &[a, b, c] = f();", "auto &[ a , b,c ] = f();");
+ verifyFormat("auto &&[a, b, c] = f();", "auto &&[ a , b,c ] = f();");
+ verifyFormat("auto const &[a, b] = f();", "auto const&[a, b] = f();");
+ verifyFormat("auto const volatile &&[a, b] = f();",
+ "auto const volatile &&[a, b] = f();");
+ verifyFormat("auto const &&[a, b] = f();", "auto const && [a, b] = f();");
+ verifyFormat("const auto &[a, b] = f();", "const auto & [a, b] = f();");
+ verifyFormat("const auto volatile &&[a, b] = f();",
+ "const auto volatile &&[a, b] = f();");
+ verifyFormat("volatile const auto &&[a, b] = f();",
+ "volatile const auto &&[a, b] = f();");
+ verifyFormat("const auto &&[a, b] = f();", "const auto && [a, b] = f();");
+
+ // Make sure we don't mistake structured bindings for lambdas.
+ FormatStyle PointerMiddle = getLLVMStyle();
+ PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyGoogleFormat("auto [a1, b]{A * i};");
+ verifyFormat("auto [a2, b]{A * i};");
+ verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
+ verifyGoogleFormat("auto const [a1, b]{A * i};");
+ verifyFormat("auto const [a2, b]{A * i};");
+ verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
+ verifyGoogleFormat("auto const& [a1, b]{A * i};");
+ verifyFormat("auto const &[a2, b]{A * i};");
+ verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
+ verifyGoogleFormat("auto const&& [a1, b]{A * i};");
+ verifyFormat("auto const &&[a2, b]{A * i};");
+ verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
+
+ verifyFormat("for (const auto &&[a, b] : some_range) {\n}",
+ "for (const auto && [a, b] : some_range) {\n}");
+ verifyFormat("for (const auto &[a, b] : some_range) {\n}",
+ "for (const auto & [a, b] : some_range) {\n}");
+ verifyFormat("for (const auto [a, b] : some_range) {\n}",
+ "for (const auto[a, b] : some_range) {\n}");
+ verifyFormat("auto [x, y](expr);", "auto[x,y] (expr);");
+ verifyFormat("auto &[x, y](expr);", "auto & [x,y] (expr);");
+ verifyFormat("auto &&[x, y](expr);", "auto && [x,y] (expr);");
+ verifyFormat("auto const &[x, y](expr);", "auto const & [x,y] (expr);");
+ verifyFormat("auto const &&[x, y](expr);", "auto const && [x,y] (expr);");
+ verifyFormat("auto [x, y]{expr};", "auto[x,y] {expr};");
+ verifyFormat("auto const &[x, y]{expr};", "auto const & [x,y] {expr};");
+ verifyFormat("auto const &&[x, y]{expr};", "auto const && [x,y] {expr};");
+
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.SpacesInSquareBrackets = true;
+ verifyFormat("auto [ a, b ] = f();", Spaces);
+ verifyFormat("auto &&[ a, b ] = f();", Spaces);
+ verifyFormat("auto &[ a, b ] = f();", Spaces);
+ verifyFormat("auto const &&[ a, b ] = f();", Spaces);
+ verifyFormat("auto const &[ a, b ] = f();", Spaces);
+}
+
+TEST_F(FormatTest, FileAndCode) {
+ EXPECT_EQ(FormatStyle::LK_C, guessLanguage("foo.c", ""));
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
+ EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
+ EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "@interface Foo\n at end"));
+ EXPECT_EQ(
+ FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
+ EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
+ EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface Foo\n at end"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int DoStuff(CGRect rect);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage(
+ "foo.h", "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));"));
+ EXPECT_EQ(
+ FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
+ // Only one of the two preprocessor regions has ObjC-like code.
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "#if A\n"
+ "#define B() C\n"
+ "#else\n"
+ "#define B() [NSString a:@\"\"]\n"
+ "#endif"));
+}
+
+TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "array[[calculator getIndex]];"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
+ EXPECT_EQ(
+ FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "[[noreturn foo] bar];"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[clang::fallthrough]];"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[using clang: fallthrough]];"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
+ EXPECT_EQ(
+ FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
+ EXPECT_EQ(
+ FormatStyle::LK_Cpp,
+ guessLanguage("foo.h",
+ "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
+}
+
+TEST_F(FormatTest, GuessLanguageWithCaret) {
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
+ EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int(^)(char, float);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int(^foo)(char, float);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int(^foo[10])(char, float);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
+ EXPECT_EQ(
+ FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
+}
+
+TEST_F(FormatTest, GuessLanguageWithPragmas) {
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "__pragma(warning(disable:))"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "#pragma(warning(disable:))"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "_Pragma(warning(disable:))"));
+}
+
+TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
+ // ASM symbolic names are identifiers that must be surrounded by [] without
+ // space in between:
+ // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
+
+ // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
+ verifyFormat(R"(//
+asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
+)");
+
+ // A list of several ASM symbolic names.
+ verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
+
+ // ASM symbolic names in inline ASM with inputs and outputs.
+ verifyFormat(R"(//
+asm("cmoveq %1, %2, %[result]"
+ : [result] "=r"(result)
+ : "r"(test), "r"(new), "[result]"(old));
+)");
+
+ // ASM symbolic names in inline ASM with no outputs.
+ verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
+}
+
+TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " asm (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d)\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " _asm (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d)\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " __asm (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d)\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " __asm__ (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d)\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " asm (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d),\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "void f() {\n"
+ " asm volatile (\"mov %[e], %[d]\"\n"
+ " : [d] \"=rm\" (d)\n"
+ " [e] \"rm\" (*e));\n"
+ "}"));
+}
+
+TEST_F(FormatTest, GuessLanguageWithChildLines) {
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
+ EXPECT_EQ(
+ FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
+ EXPECT_EQ(
+ FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
+}
+
+TEST_F(FormatTest, GetLanguageByComment) {
+ EXPECT_EQ(FormatStyle::LK_C,
+ guessLanguage("foo.h", "// clang-format Language: C\n"
+ "int i;"));
+ EXPECT_EQ(FormatStyle::LK_Cpp,
+ guessLanguage("foo.h", "// clang-format Language: Cpp\n"
+ "int DoStuff(CGRect rect);"));
+ EXPECT_EQ(FormatStyle::LK_ObjC,
+ guessLanguage("foo.h", "// clang-format Language: ObjC\n"
+ "int i;"));
+}
+
+TEST_F(FormatTest, TypenameMacros) {
+ std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
+
+ // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
+ FormatStyle Google = getGoogleStyleWithColumns(0);
+ Google.TypenameMacros = TypenameMacros;
+ verifyFormat("struct foo {\n"
+ " int bar;\n"
+ " TAILQ_ENTRY(a) bleh;\n"
+ "};",
+ Google);
+
+ FormatStyle Macros = getLLVMStyle();
+ Macros.TypenameMacros = TypenameMacros;
+
+ verifyFormat("STACK_OF(int) a;", Macros);
+ verifyFormat("STACK_OF(int) *a;", Macros);
+ verifyFormat("STACK_OF(int const *) *a;", Macros);
+ verifyFormat("STACK_OF(int *const) *a;", Macros);
+ verifyFormat("STACK_OF(int, string) a;", Macros);
+ verifyFormat("STACK_OF(LIST(int)) a;", Macros);
+ verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
+ verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
+ verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
+ verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
+ verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
+
+ Macros.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("STACK_OF(int)* a;", Macros);
+ verifyFormat("STACK_OF(int*)* a;", Macros);
+ verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
+ verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
+ verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
+}
+
+TEST_F(FormatTest, AtomicQualifier) {
+ // Check that we treate _Atomic as a type and not a function call
+ FormatStyle Google = getGoogleStyleWithColumns(0);
+ verifyFormat("struct foo {\n"
+ " int a1;\n"
+ " _Atomic(a) a2;\n"
+ " _Atomic(_Atomic(int)* const) a3;\n"
+ "};",
+ Google);
+ verifyFormat("_Atomic(uint64_t) a;");
+ verifyFormat("_Atomic(uint64_t) *a;");
+ verifyFormat("_Atomic(uint64_t const *) *a;");
+ verifyFormat("_Atomic(uint64_t *const) *a;");
+ verifyFormat("_Atomic(const uint64_t *) *a;");
+ verifyFormat("_Atomic(uint64_t) a;");
+ verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
+ verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
+ verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
+ verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
+
+ verifyFormat("_Atomic(uint64_t) *s(InitValue);");
+ verifyFormat("_Atomic(uint64_t) *s{InitValue};");
+ FormatStyle Style = getLLVMStyle();
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
+ verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
+ verifyFormat("_Atomic(int)* a;", Style);
+ verifyFormat("_Atomic(int*)* a;", Style);
+ verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
+
+ Style.SpacesInParens = FormatStyle::SIPO_Custom;
+ Style.SpacesInParensOptions.InCStyleCasts = true;
+ verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
+ Style.SpacesInParensOptions.InCStyleCasts = false;
+ Style.SpacesInParensOptions.Other = true;
+ verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
+ verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
+}
+
+TEST_F(FormatTest, C11Generic) {
+ verifyFormat("_Generic(x, int: 1, default: 0)");
+ verifyFormat("#define cbrt(X) _Generic((X), float: cbrtf, default: cbrt)(X)");
+ verifyFormat("_Generic(x, const char *: 1, char *const: 16, int: 8);");
+ verifyFormat("_Generic(x, int: f1, const int: f2)();");
+ verifyFormat("_Generic(x, struct A: 1, void (*)(void): 2);");
+
+ verifyFormat("_Generic(x,\n"
+ " float: f,\n"
+ " default: d,\n"
+ " long double: ld,\n"
+ " float _Complex: fc,\n"
+ " double _Complex: dc,\n"
+ " long double _Complex: ldc)");
+
+ verifyFormat("while (_Generic(x, //\n"
+ " long: x)(x) > x) {\n"
+ "}");
+ verifyFormat("while (_Generic(x, //\n"
+ " long: x)(x)) {\n"
+ "}");
+ verifyFormat("x(_Generic(x, //\n"
+ " long: x)(x));");
+
+ FormatStyle Style = getLLVMStyle();
+ Style.ColumnLimit = 40;
+ verifyFormat("#define LIMIT_MAX(T) \\\n"
+ " _Generic(((T)0), \\\n"
+ " unsigned int: UINT_MAX, \\\n"
+ " unsigned long: ULONG_MAX, \\\n"
+ " unsigned long long: ULLONG_MAX)",
+ Style);
+ verifyFormat("_Generic(x,\n"
+ " struct A: 1,\n"
+ " void (*)(void): 2);",
+ Style);
+
+ Style.ContinuationIndentWidth = 2;
+ verifyFormat("_Generic(x,\n"
+ " struct A: 1,\n"
+ " void (*)(void): 2);",
+ Style);
+}
+
+TEST_F(FormatTest, AmbersandInLamda) {
+ // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
+ FormatStyle AlignStyle = getLLVMStyle();
+ AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
+ AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
+ verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
+}
+
+TEST_F(FormatTest, TrailingReturnTypeAuto) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("[]() -> auto { return Val; }", Style);
+ verifyFormat("[]() -> auto * { return Val; }", Style);
+ verifyFormat("[]() -> auto & { return Val; }", Style);
+ verifyFormat("auto foo() -> auto { return Val; }", Style);
+ verifyFormat("auto foo() -> auto * { return Val; }", Style);
+ verifyFormat("auto foo() -> auto & { return Val; }", Style);
+}
+
+TEST_F(FormatTest, SpacesInConditionalStatement) {
+ FormatStyle Spaces = getLLVMStyle();
+ Spaces.IfMacros.clear();
+ Spaces.IfMacros.push_back("MYIF");
+ Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+ Spaces.SpacesInParensOptions.InConditionalStatements = true;
+ verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces);
+ verifyFormat("if ( !a )\n return;", Spaces);
+ verifyFormat("if ( a )\n return;", Spaces);
+ verifyFormat("if constexpr ( a )\n return;", Spaces);
+ verifyFormat("MYIF ( a )\n return;", Spaces);
+ verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces);
+ verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces);
+ verifyFormat("switch ( a )\ncase 1:\n return;", Spaces);
+ verifyFormat("while ( a )\n return;", Spaces);
+ verifyFormat("while ( (a && b) )\n return;", Spaces);
+ verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
+ verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
+ // Check that space on the left of "::" is inserted as expected at beginning
+ // of condition.
+ verifyFormat("while ( ::func() )\n return;", Spaces);
+
+ // Check impact of ControlStatementsExceptControlMacros is honored.
+ Spaces.SpaceBeforeParens =
+ FormatStyle::SBPO_ControlStatementsExceptControlMacros;
+ verifyFormat("MYIF( a )\n return;", Spaces);
+ verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces);
+ verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces);
+}
+
+TEST_F(FormatTest, SpaceInEmptyBraces) {
+ constexpr StringRef Code("void f() {}\n"
+ "class Unit {};\n"
+ "auto a = [] {};\n"
+ "int x{};");
+ verifyFormat(Code);
+
+ auto Style = getWebKitStyle();
+ EXPECT_EQ(Style.SpaceInEmptyBraces, FormatStyle::SIEB_Always);
+
+ verifyFormat("void f() { }\n"
+ "class Unit { };\n"
+ "auto a = [] { };\n"
+ "int x { };",
+ Code, Style);
+
+ Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
+ verifyFormat("void f() { }\n"
+ "class Unit { };\n"
+ "auto a = [] { };\n"
+ "int x {};",
+ Code, Style);
+}
+
+TEST_F(FormatTest, AlternativeOperators) {
+ // Test case for ensuring alternate operators are not
+ // combined with their right most neighbour.
+ verifyFormat("int a and b;");
+ verifyFormat("int a and_eq b;");
+ verifyFormat("int a bitand b;");
+ verifyFormat("int a bitor b;");
+ verifyFormat("int a compl b;");
+ verifyFormat("int a not b;");
+ verifyFormat("int a not_eq b;");
+ verifyFormat("int a or b;");
+ verifyFormat("int a xor b;");
+ verifyFormat("int a xor_eq b;");
+ verifyFormat("return this not_eq bitand other;");
+ verifyFormat("bool operator not_eq(const X bitand other)");
+
+ verifyFormat("int a and 5;");
+ verifyFormat("int a and_eq 5;");
+ verifyFormat("int a bitand 5;");
+ verifyFormat("int a bitor 5;");
+ verifyFormat("int a compl 5;");
+ verifyFormat("int a not 5;");
+ verifyFormat("int a not_eq 5;");
+ verifyFormat("int a or 5;");
+ verifyFormat("int a xor 5;");
+ verifyFormat("int a xor_eq 5;");
+
+ verifyFormat("int a compl(5);");
+ verifyFormat("int a not(5);");
+
+ verifyFormat("compl foo();"); // ~foo();
+ verifyFormat("foo() <%%>"); // foo() {}
+ verifyFormat("void foo() <%%>"); // void foo() {}
+ verifyFormat("int a<:1:>;"); // int a[1];
+ verifyFormat("%:define ABC abc"); // #define ABC abc
+ verifyFormat("%:%:"); // ##
+
+ verifyFormat("return not ::f();");
+ verifyFormat("return not *foo;");
+
+ verifyFormat("a = v(not;);\n"
+ "c = v(not x);\n"
+ "d = v(not 1);\n"
+ "e = v(not 123.f);");
+
+ verifyNoChange("#define ASSEMBLER_INSTRUCTION_LIST(V) \\\n"
+ " V(and) \\\n"
+ " V(not) \\\n"
+ " V(other)",
+ getLLVMStyleWithColumns(40));
+}
+
+TEST_F(FormatTest, STLWhileNotDefineChed) {
+ verifyFormat("#if defined(while)\n"
+ "#define while EMIT WARNING C4005\n"
+ "#endif // while");
+}
+
+TEST_F(FormatTest, OperatorSpacing) {
+ FormatStyle Style = getLLVMStyle();
+ Style.PointerAlignment = FormatStyle::PAS_Right;
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("Foo::operator void *();", Style);
+ verifyFormat("Foo::operator void **();", Style);
+ verifyFormat("Foo::operator void *&();", Style);
+ verifyFormat("Foo::operator void *&&();", Style);
+ verifyFormat("Foo::operator void const *();", Style);
+ verifyFormat("Foo::operator void const **();", Style);
+ verifyFormat("Foo::operator void const *&();", Style);
+ verifyFormat("Foo::operator void const *&&();", Style);
+ verifyFormat("Foo::operator()(void *);", Style);
+ verifyFormat("Foo::operator*(void *);", Style);
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("Foo::operator**();", Style);
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("Foo::operator<int> *();", Style);
+ verifyFormat("Foo::operator<Foo> *();", Style);
+ verifyFormat("Foo::operator<int> **();", Style);
+ verifyFormat("Foo::operator<Foo> **();", Style);
+ verifyFormat("Foo::operator<int> &();", Style);
+ verifyFormat("Foo::operator<Foo> &();", Style);
+ verifyFormat("Foo::operator<int> &&();", Style);
+ verifyFormat("Foo::operator<Foo> &&();", Style);
+ verifyFormat("Foo::operator<int> *&();", Style);
+ verifyFormat("Foo::operator<Foo> *&();", Style);
+ verifyFormat("Foo::operator<int> *&&();", Style);
+ verifyFormat("Foo::operator<Foo> *&&();", Style);
+ verifyFormat("operator*(int (*)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("Foo::operator void &();", Style);
+ verifyFormat("Foo::operator void const &();", Style);
+ verifyFormat("Foo::operator()(void &);", Style);
+ verifyFormat("Foo::operator&(void &);", Style);
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("operator&(int (&)(), class Foo);", Style);
+ verifyFormat("operator&&(int (&)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("Foo::operator**();", Style);
+ verifyFormat("Foo::operator void &&();", Style);
+ verifyFormat("Foo::operator void const &&();", Style);
+ verifyFormat("Foo::operator()(void &&);", Style);
+ verifyFormat("Foo::operator&&(void &&);", Style);
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("operator&&(int (&&)(), class Foo);", Style);
+ verifyFormat("operator const nsTArrayRight<E> &()", Style);
+ verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
+ Style);
+ verifyFormat("operator void **()", Style);
+ verifyFormat("operator const FooRight<Object> &()", Style);
+ verifyFormat("operator const FooRight<Object> *()", Style);
+ verifyFormat("operator const FooRight<Object> **()", Style);
+ verifyFormat("operator const FooRight<Object> *&()", Style);
+ verifyFormat("operator const FooRight<Object> *&&()", Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("Foo::operator**();", Style);
+ verifyFormat("Foo::operator void*();", Style);
+ verifyFormat("Foo::operator void**();", Style);
+ verifyFormat("Foo::operator void*&();", Style);
+ verifyFormat("Foo::operator void*&&();", Style);
+ verifyFormat("Foo::operator void const*();", Style);
+ verifyFormat("Foo::operator void const**();", Style);
+ verifyFormat("Foo::operator void const*&();", Style);
+ verifyFormat("Foo::operator void const*&&();", Style);
+ verifyFormat("Foo::operator/*comment*/ void*();", Style);
+ verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
+ verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
+ verifyFormat("Foo::operator()(void*);", Style);
+ verifyFormat("Foo::operator*(void*);", Style);
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("Foo::operator<int>*();", Style);
+ verifyFormat("Foo::operator<Foo>*();", Style);
+ verifyFormat("Foo::operator<int>**();", Style);
+ verifyFormat("Foo::operator<Foo>**();", Style);
+ verifyFormat("Foo::operator<Foo>*&();", Style);
+ verifyFormat("Foo::operator<int>&();", Style);
+ verifyFormat("Foo::operator<Foo>&();", Style);
+ verifyFormat("Foo::operator<int>&&();", Style);
+ verifyFormat("Foo::operator<Foo>&&();", Style);
+ verifyFormat("Foo::operator<int>*&();", Style);
+ verifyFormat("Foo::operator<Foo>*&();", Style);
+ verifyFormat("operator*(int (*)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("Foo::operator void&();", Style);
+ verifyFormat("Foo::operator void const&();", Style);
+ verifyFormat("Foo::operator/*comment*/ void&();", Style);
+ verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
+ verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
+ verifyFormat("Foo::operator()(void&);", Style);
+ verifyFormat("Foo::operator&(void&);", Style);
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("operator&(int (&)(), class Foo);", Style);
+ verifyFormat("operator&(int (&&)(), class Foo);", Style);
+ verifyFormat("operator&&(int (&&)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("Foo::operator void&&();", Style);
+ verifyFormat("Foo::operator void const&&();", Style);
+ verifyFormat("Foo::operator/*comment*/ void&&();", Style);
+ verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
+ verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
+ verifyFormat("Foo::operator()(void&&);", Style);
+ verifyFormat("Foo::operator&&(void&&);", Style);
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("operator&&(int (&&)(), class Foo);", Style);
+ verifyFormat("operator const nsTArrayLeft<E>&()", Style);
+ verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
+ Style);
+ verifyFormat("operator void**()", Style);
+ verifyFormat("operator const FooLeft<Object>&()", Style);
+ verifyFormat("operator const FooLeft<Object>*()", Style);
+ verifyFormat("operator const FooLeft<Object>**()", Style);
+ verifyFormat("operator const FooLeft<Object>*&()", Style);
+ verifyFormat("operator const FooLeft<Object>*&&()", Style);
+
+ // PR45107
+ verifyFormat("operator Vector<String>&();", Style);
+ verifyFormat("operator const Vector<String>&();", Style);
+ verifyFormat("operator foo::Bar*();", Style);
+ verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
+ verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
+ Style);
+
+ Style.PointerAlignment = FormatStyle::PAS_Middle;
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("Foo::operator void *();", Style);
+ verifyFormat("Foo::operator()(void *);", Style);
+ verifyFormat("Foo::operator*(void *);", Style);
+ verifyFormat("Foo::operator*();", Style);
+ verifyFormat("operator*(int (*)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("Foo::operator void &();", Style);
+ verifyFormat("Foo::operator void const &();", Style);
+ verifyFormat("Foo::operator()(void &);", Style);
+ verifyFormat("Foo::operator&(void &);", Style);
+ verifyFormat("Foo::operator&();", Style);
+ verifyFormat("operator&(int (&)(), class Foo);", Style);
+
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("Foo::operator void &&();", Style);
+ verifyFormat("Foo::operator void const &&();", Style);
+ verifyFormat("Foo::operator()(void &&);", Style);
+ verifyFormat("Foo::operator&&(void &&);", Style);
+ verifyFormat("Foo::operator&&();", Style);
+ verifyFormat("operator&&(int (&&)(), class Foo);", Style);
+}
+
+TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
+ FormatStyle Style = getLLVMStyle();
+ // PR46157
+ verifyFormat("foo(operator+, -42);", Style);
+ verifyFormat("foo(operator++, -42);", Style);
+ verifyFormat("foo(operator--, -42);", Style);
+ verifyFormat("foo(-42, operator--);", Style);
+ verifyFormat("foo(-42, operator, );", Style);
+ verifyFormat("foo(operator, , -42);", Style);
+}
+
+TEST_F(FormatTest, LineSpliceWithTrailingWhitespace) {
+ auto Style = getLLVMStyle();
+ Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
+ Style.UseTab = FormatStyle::UT_Never;
+
+ verifyFormat("int i;", " \\ \n"
+ " int i;");
+ verifyFormat("#define FOO(args) \\\n"
+ " struct a {};",
+ "#define FOO( args ) \\ \n"
+ "struct a{\\\t\t\t\n"
+ " };",
+ Style);
+}
+
+TEST_F(FormatTest, WhitespaceSensitiveMacros) {
+ FormatStyle Style = getLLVMStyle();
+ Style.WhitespaceSensitiveMacros.push_back("FOO");
+
+ // Newlines are important here.
+ verifyNoChange("FOO(1+2 )\n", Style);
+ verifyNoChange("FOO(a:b:c)\n", Style);
+
+ // Don't use the helpers here, since 'mess up' will change the whitespace
+ // and these are all whitespace sensitive by definition
+ verifyNoChange("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style);
+ verifyNoChange("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style);
+ verifyNoChange("FOO(String-ized&Messy+But,: :Still=Intentional);", Style);
+ verifyNoChange("FOO(String-ized&Messy+But,: :\n"
+ " Still=Intentional);",
+ Style);
+ Style.AlignConsecutiveAssignments.Enabled = true;
+ verifyNoChange("FOO(String-ized=&Messy+But,: :\n"
+ " Still=Intentional);",
+ Style);
+
+ Style.ColumnLimit = 21;
+ verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
+}
+
+TEST_F(FormatTest, SkipMacroDefinitionBody) {
+ auto Style = getLLVMStyle();
+ Style.SkipMacroDefinitionBody = true;
+
+ verifyFormat("#define A", "#define A", Style);
+ verifyFormat("#define A a aa", "#define A a aa", Style);
+ verifyNoChange("#define A b", Style);
+ verifyNoChange("#define A ( args )", Style);
+ verifyNoChange("#define A ( args ) = func ( args )", Style);
+ verifyNoChange("#define A ( args ) { int a = 1 ; }", Style);
+ verifyNoChange("#define A ( args ) \\\n"
+ " {\\\n"
+ " int a = 1 ;\\\n"
+ "}",
+ Style);
+
+ verifyNoChange("#define A x:", Style);
+ verifyNoChange("#define A a. b", Style);
+
+ // Surrounded with formatted code.
+ verifyFormat("int a;\n"
+ "#define A a\n"
+ "int a;",
+ "int a ;\n"
+ "#define A a\n"
+ "int a ;",
+ Style);
+
+ // Columns are not broken when a limit is set.
+ Style.ColumnLimit = 10;
+ verifyFormat("#define A a a a a", " # define A a a a a ", Style);
+ verifyNoChange("#define A a a a a", Style);
+
+ Style.ColumnLimit = 15;
+ verifyFormat("#define A // a\n"
+ " // very\n"
+ " // long\n"
+ " // comment",
+ "#define A //a very long comment", Style);
+ Style.ColumnLimit = 0;
+
+ // Multiline definition.
+ verifyNoChange("#define A \\\n"
+ "Line one with spaces . \\\n"
+ " Line two.",
+ Style);
+ verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a \\\n"
+ "a",
+ Style);
+ Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
+ verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a \\\n"
+ "a",
+ Style);
+ Style.AlignEscapedNewlines = FormatStyle::ENAS_Right;
+ verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a \\\n"
+ "a",
+ Style);
+
+ Style.IndentPPDirectives = FormatStyle::PPDIS_Leave;
+ verifyNoChange("#if A\n"
+ "#define A a\n"
+ "#endif",
+ Style);
+ verifyNoChange("#if A\n"
+ " #define A a\n"
+ "#endif",
+ Style);
+ verifyNoChange("#if A\n"
+ "# define A a\n"
+ "#endif",
+ Style);
+
+ // Adjust indendations but don't change the definition.
+ Style.IndentPPDirectives = FormatStyle::PPDIS_None;
+ verifyNoChange("#if A\n"
+ "#define A a\n"
+ "#endif",
+ Style);
+ verifyFormat("#if A\n"
+ "#define A a\n"
+ "#endif",
+ "#if A\n"
+ " #define A a\n"
+ "#endif",
+ Style);
+ Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+ verifyNoChange("#if A\n"
+ "# define A a\n"
+ "#endif",
+ Style);
+ verifyFormat("#if A\n"
+ "# define A a\n"
+ "#endif",
+ "#if A\n"
+ " #define A a\n"
+ "#endif",
+ Style);
+ Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
+ verifyNoChange("#if A\n"
+ " #define A a\n"
+ "#endif",
+ Style);
+ verifyFormat("#if A\n"
+ " #define A a\n"
+ "#endif",
+ "#if A\n"
+ " # define A a\n"
+ "#endif",
+ Style);
+
+ Style.IndentPPDirectives = FormatStyle::PPDIS_None;
+ // SkipMacroDefinitionBody should not affect other PP directives
+ verifyFormat("#if !defined(A)\n"
+ "#define A a\n"
+ "#endif",
+ "#if ! defined ( A )\n"
+ " #define A a\n"
+ "#endif",
+ Style);
+
+ // With comments.
+ verifyFormat("/* */ #define A a // a a", "/* */ # define A a // a a",
+ Style);
+ verifyNoChange("/* */ #define A a // a a", Style);
+
+ verifyFormat("int a; // a\n"
+ "#define A // a\n"
+ "int aaa; // a",
+ "int a; // a\n"
+ "#define A // a\n"
+ "int aaa; // a",
+ Style);
+
+ verifyNoChange(
+ "#define MACRO_WITH_COMMENTS() \\\n"
+ " public: \\\n"
+ " /* Documentation parsed by Doxygen for the following method. */ \\\n"
+ " static MyType getClassTypeId(); \\\n"
+ " /** Normal comment for the following method. */ \\\n"
+ " virtual MyType getTypeId() const;",
+ Style);
+
+ // multiline macro definitions
+ verifyNoChange("#define A a\\\n"
+ " A a \\\n "
+ " A a",
+ Style);
+ verifyNoChange("#define MY_MACRO \\\n"
+ " /*foo*//*bar*/ \\\n"
+ " /* comment */ \\\n"
+ " 1",
+ Style);
+}
+
+TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
+ // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
+ // test its interaction with line wrapping
+ FormatStyle Style = getLLVMStyleWithColumns(80);
+ verifyFormat("namespace {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace",
+ Style);
+
+ verifyFormat("namespace AAA {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace AAA",
+ Style);
+
+ verifyFormat("namespace Averyveryveryverylongnamespace {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace Averyveryveryverylongnamespace",
+ "namespace Averyveryveryverylongnamespace {\n"
+ "int i;\n"
+ "int j;\n"
+ "}",
+ Style);
+
+ verifyFormat(
+ "namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
+ " went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace\n"
+ " // "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
+ "went::mad::now",
+ "namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::"
+ "just::gave::up::and_::went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "}",
+ Style);
+
+ // This used to duplicate the comment again and again on subsequent runs
+ verifyFormat(
+ "namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
+ " went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace\n"
+ " // "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
+ "went::mad::now",
+ "namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::"
+ "just::gave::up::and_::went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace\n"
+ " // "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
+ "and_::went::mad::now",
+ Style);
+}
+
+TEST_F(FormatTest, LikelyUnlikely) {
+ FormatStyle Style = getLLVMStyle();
+
+ verifyFormat("if (argc > 5) [[unlikely]] {\n"
+ " return 29;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (argc > 5) [[likely]] {\n"
+ " return 29;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (argc > 5) [[unlikely]] {\n"
+ " return 29;\n"
+ "} else [[likely]] {\n"
+ " return 42;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (argc > 5) [[unlikely]] {\n"
+ " return 29;\n"
+ "} else if (argc > 10) [[likely]] {\n"
+ " return 99;\n"
+ "} else {\n"
+ " return 42;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
+ " return 29;\n"
+ "}",
+ Style);
+
+ verifyFormat("if (argc > 5) [[unlikely]]\n"
+ " return 29;",
+ Style);
+ verifyFormat("if (argc > 5) [[likely]]\n"
+ " return 29;",
+ Style);
+
+ verifyFormat("while (limit > 0) [[unlikely]] {\n"
+ " --limit;\n"
+ "}",
+ Style);
+ verifyFormat("for (auto &limit : limits) [[likely]] {\n"
+ " --limit;\n"
+ "}",
+ Style);
+
+ verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
+ " --limit;",
+ Style);
+ verifyFormat("while (limit > 0) [[likely]]\n"
+ " --limit;",
+ Style);
+
+ Style.AttributeMacros.push_back("UNLIKELY");
+ Style.AttributeMacros.push_back("LIKELY");
+ verifyFormat("if (argc > 5) UNLIKELY\n"
+ " return 29;",
+ Style);
+
+ verifyFormat("if (argc > 5) UNLIKELY {\n"
+ " return 29;\n"
+ "}",
+ Style);
+ verifyFormat("if (argc > 5) UNLIKELY {\n"
+ " return 29;\n"
+ "} else [[likely]] {\n"
+ " return 42;\n"
+ "}",
+ Style);
+ verifyFormat("if (argc > 5) UNLIKELY {\n"
+ " return 29;\n"
+ "} else LIKELY {\n"
+ " return 42;\n"
+ "}",
+ Style);
+ verifyFormat("if (argc > 5) [[unlikely]] {\n"
+ " return 29;\n"
+ "} else LIKELY {\n"
+ " return 42;\n"
+ "}",
+ Style);
+
+ verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
+ " --limit;\n"
+ "}",
+ Style);
+ verifyFormat("while (limit > 0) LIKELY {\n"
+ " --limit;\n"
+ "}",
+ Style);
+
+ verifyFormat("while (limit > 0) UNLIKELY\n"
+ " --limit;",
+ Style);
+ verifyFormat("for (auto &limit : limits) LIKELY\n"
+ " --limit;",
+ Style);
+}
+
+TEST_F(FormatTest, PenaltyIndentedWhitespace) {
+ verifyFormat("Constructor()\n"
+ " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaa(aaaaaaaaaaaaaaaaaa, "
+ "aaaaaaaaaaaaaaaaaat))");
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaa), "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
+
+ FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
+ StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
+ verifyFormat("Constructor()\n"
+ " : aaaaaa(aaaaaa),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
+ StyleWithWhitespacePenalty);
+ verifyFormat("Constructor()\n"
+ " : aaaaaaaaaaaaa(aaaaaa), "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
+ StyleWithWhitespacePenalty);
+}
+
+TEST_F(FormatTest, LLVMDefaultStyle) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("extern \"C\" {\n"
+ "int foo();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, GNUDefaultStyle) {
+ FormatStyle Style = getGNUStyle();
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ " int foo ();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, MozillaDefaultStyle) {
+ FormatStyle Style = getMozillaStyle();
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ " int foo();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, GoogleDefaultStyle) {
+ FormatStyle Style = getGoogleStyle();
+ verifyFormat("extern \"C\" {\n"
+ "int foo();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, ChromiumDefaultStyle) {
+ FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
+ verifyFormat("extern \"C\" {\n"
+ "int foo();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, MicrosoftDefaultStyle) {
+ FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_Cpp);
+ verifyFormat("extern \"C\"\n"
+ "{\n"
+ " int foo();\n"
+ "}",
+ Style);
+}
+TEST_F(FormatTest, WebKitDefaultStyle) {
+ FormatStyle Style = getWebKitStyle();
+ verifyFormat("extern \"C\" {\n"
+ "int foo();\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, Concepts) {
+ EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
+ FormatStyle::BBCDS_Always);
+
+ // The default in LLVM style is REI_OuterScope, but these tests were written
+ // when the default was REI_Keyword.
+ FormatStyle Style = getLLVMStyle();
+ Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
+
+ verifyFormat("template <typename T>\n"
+ "concept True = true;");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = ((false || foo()) && C2<T>) ||\n"
+ " (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
+ getLLVMStyleWithColumns(60));
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
+ "sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = true && requires(T t) {\n"
+ " t.bar();\n"
+ " t.baz();\n"
+ " } && sizeof(T) <= 8;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = true && requires(T t) { // Comment\n"
+ " t.bar();\n"
+ " t.baz();\n"
+ " } && sizeof(T) <= 8;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
+ "sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = Unit<T> && !DerivedUnit<T>;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = Unit<T> && !(DerivedUnit<T>);");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = Unit<T> && !!DerivedUnit<T>;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
+ "&& sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck =\n"
+ " static_cast<bool>(0) || requires(T t) { t.bar(); } && "
+ "sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
+ "&& sizeof(T) <= 8;");
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept DelayedCheck =\n"
+ " (bool)(0) || requires(T t) { t.bar(); } && sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
+ "&& sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
+ "sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
+ " requires(T t) {\n"
+ " t.bar();\n"
+ " t.baz();\n"
+ " } && sizeof(T) <= 8 && !(4 < 3);",
+ getLLVMStyleWithColumns(60));
+
+ verifyFormat("template <typename T>\n"
+ "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = foo();");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = foo(T());");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = foo(T{});");
+
+ verifyFormat("template <typename T>\n"
+ "concept Size = V<sizeof(T)>::Value > 5;");
+
+ verifyFormat("template <typename T>\n"
+ "concept True = S<T>::Value;");
+
+ verifyFormat("template <S T>\n"
+ "concept True = T.field;");
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
+ " sizeof(T) <= 8;");
+
+ // FIXME: This is misformatted because the fake l paren starts at bool, not at
+ // the lambda l square.
+ verifyFormat("template <typename T>\n"
+ "concept C = [] -> bool { return true; }() && requires(T t) { "
+ "t.bar(); } &&\n"
+ " sizeof(T) <= 8;");
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
+ " requires(T t) { t.bar(); } && sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = decltype([]() { return std::true_type{}; "
+ "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
+ getLLVMStyleWithColumns(120));
+
+ verifyFormat("template <typename T>\n"
+ "concept C = decltype([]() -> std::true_type { return {}; "
+ "}())::value &&\n"
+ " requires(T t) { t.bar(); } && sizeof(T) <= 8;");
+
+ verifyFormat("template <typename T>\n"
+ "concept C = true;\n"
+ "Foo Bar;");
+
+ verifyFormat("template <typename T>\n"
+ "concept Hashable = requires(T a) {\n"
+ " { std::hash<T>{}(a) } -> "
+ "std::convertible_to<std::size_t>;\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept EqualityComparable = requires(T a, T b) {\n"
+ " { a == b } -> std::same_as<bool>;\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept EqualityComparable = requires(T a, T b) {\n"
+ " { a == b } -> std::same_as<bool>;\n"
+ " { a != b } -> std::same_as<bool>;\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept WeakEqualityComparable = requires(T a, T b) {\n"
+ " { a == b };\n"
+ " { a != b };\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept HasSizeT = requires { typename T::size_t; };");
+
+ verifyFormat("template <typename T>\n"
+ "concept Semiregular =\n"
+ " DefaultConstructible<T> && CopyConstructible<T> && "
+ "CopyAssignable<T> &&\n"
+ " requires(T a, std::size_t n) {\n"
+ " requires Same<T *, decltype(&a)>;\n"
+ " { a.~T() } noexcept;\n"
+ " requires Same<T *, decltype(new T)>;\n"
+ " requires Same<T *, decltype(new T[n])>;\n"
+ " { delete new T; };\n"
+ " { delete new T[n]; };\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept Semiregular =\n"
+ " requires(T a, std::size_t n) {\n"
+ " requires Same<T *, decltype(&a)>;\n"
+ " { a.~T() } noexcept;\n"
+ " requires Same<T *, decltype(new T)>;\n"
+ " requires Same<T *, decltype(new T[n])>;\n"
+ " { delete new T; };\n"
+ " { delete new T[n]; };\n"
+ " { new T } -> std::same_as<T *>;\n"
+ " } && DefaultConstructible<T> && CopyConstructible<T> && "
+ "CopyAssignable<T>;",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept Semiregular =\n"
+ " DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
+ " requires Same<T *, decltype(&a)>;\n"
+ " { a.~T() } noexcept;\n"
+ " requires Same<T *, decltype(new T)>;\n"
+ " requires Same<T *, decltype(new "
+ "T[n])>;\n"
+ " { delete new T; };\n"
+ " { delete new T[n]; };\n"
+ " } && CopyConstructible<T> && "
+ "CopyAssignable<T>;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept Two = requires(T t) {\n"
+ " { t.foo() } -> std::same_as<Bar>;\n"
+ " } && requires(T &&t) {\n"
+ " { t.foo() } -> std::same_as<Bar &&>;\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept C = requires(T x) {\n"
+ " { *x } -> std::convertible_to<typename T::inner>;\n"
+ " { x + 1 } noexcept -> std::same_as<int>;\n"
+ " { x * 1 } -> std::convertible_to<T>;\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept C = requires(T x) {\n"
+ " {\n"
+ " long_long_long_function_call(1, 2, 3, 4, 5)\n"
+ " } -> long_long_concept_name<T>;\n"
+ " {\n"
+ " long_long_long_function_call(1, 2, 3, 4, 5)\n"
+ " } noexcept -> long_long_concept_name<T>;\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T, typename U = T>\n"
+ "concept Swappable = requires(T &&t, U &&u) {\n"
+ " swap(std::forward<T>(t), std::forward<U>(u));\n"
+ " swap(std::forward<U>(u), std::forward<T>(t));\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T, typename U>\n"
+ "concept Common = requires(T &&t, U &&u) {\n"
+ " typename CommonType<T, U>;\n"
+ " { CommonType<T, U>(std::forward<T>(t)) };\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T, typename U>\n"
+ "concept Common = requires(T &&t, U &&u) {\n"
+ " typename CommonType<T, U>;\n"
+ " { CommonType<T, U>{std::forward<T>(t)} };\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept C = requires(T t) {\n"
+ " requires Bar<T> && Foo<T>;\n"
+ " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept HasFoo = requires(T t) {\n"
+ " { t.foo() };\n"
+ " t.foo();\n"
+ " };\n"
+ "template <typename T>\n"
+ "concept HasBar = requires(T t) {\n"
+ " { t.bar() };\n"
+ " t.bar();\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept Large = sizeof(T) > 10;");
+
+ verifyFormat("template <typename T, typename U>\n"
+ "concept FooableWith = requires(T t, U u) {\n"
+ " typename T::foo_type;\n"
+ " { t.foo(u) } -> typename T::foo_type;\n"
+ " t++;\n"
+ " };\n"
+ "void doFoo(FooableWith<int> auto t) { t.foo(3); }",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept Context = is_specialization_of_v<context, T>;");
+
+ verifyFormat("template <typename T>\n"
+ "concept Node = std::is_object_v<T>;");
+
+ verifyFormat("template <class T>\n"
+ "concept integral = __is_integral(T);");
+
+ verifyFormat("template <class T>\n"
+ "concept is2D = __array_extent(T, 1) == 2;");
+
+ verifyFormat("template <class T>\n"
+ "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
+
+ verifyFormat("template <class T, class T2>\n"
+ "concept Same = __is_same_as<T, T2>;");
+
+ verifyFormat(
+ "template <class _InIt, class _OutIt>\n"
+ "concept _Can_reread_dest =\n"
+ " std::forward_iterator<_OutIt> &&\n"
+ " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
+
+ Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
+
+ verifyFormat(
+ "template <typename T>\n"
+ "concept C = requires(T t) {\n"
+ " requires Bar<T> && Foo<T>;\n"
+ " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept HasFoo = requires(T t) {\n"
+ " { t.foo() };\n"
+ " t.foo();\n"
+ " };\n"
+ "template <typename T>\n"
+ "concept HasBar = requires(T t) {\n"
+ " { t.bar() };\n"
+ " t.bar();\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T> concept True = true;", Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept C = decltype([]() -> std::true_type { return {}; "
+ "}())::value &&\n"
+ " requires(T t) { t.bar(); } && sizeof(T) <= 8;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "concept Semiregular =\n"
+ " DefaultConstructible<T> && CopyConstructible<T> && "
+ "CopyAssignable<T> &&\n"
+ " requires(T a, std::size_t n) {\n"
+ " requires Same<T *, decltype(&a)>;\n"
+ " { a.~T() } noexcept;\n"
+ " requires Same<T *, decltype(new T)>;\n"
+ " requires Same<T *, decltype(new T[n])>;\n"
+ " { delete new T; };\n"
+ " { delete new T[n]; };\n"
+ " };",
+ Style);
+
+ Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
+
+ verifyFormat("template <typename T> concept C =\n"
+ " requires(T t) {\n"
+ " requires Bar<T> && Foo<T>;\n"
+ " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
+ " { t.foo() };\n"
+ " t.foo();\n"
+ " };\n"
+ "template <typename T> concept HasBar = requires(T t) {\n"
+ " { t.bar() };\n"
+ " t.bar();\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T> concept True = true;", Style);
+
+ verifyFormat(
+ "template <typename T> concept C =\n"
+ " decltype([]() -> std::true_type { return {}; }())::value &&\n"
+ " requires(T t) { t.bar(); } && sizeof(T) <= 8;",
+ Style);
+
+ verifyFormat("template <typename T> concept Semiregular =\n"
+ " DefaultConstructible<T> && CopyConstructible<T> && "
+ "CopyAssignable<T> &&\n"
+ " requires(T a, std::size_t n) {\n"
+ " requires Same<T *, decltype(&a)>;\n"
+ " { a.~T() } noexcept;\n"
+ " requires Same<T *, decltype(new T)>;\n"
+ " requires Same<T *, decltype(new T[n])>;\n"
+ " { delete new T; };\n"
+ " { delete new T[n]; };\n"
+ " };",
+ Style);
+
+ // The following tests are invalid C++, we just want to make sure we don't
+ // assert.
+ verifyNoCrash("template <typename T>\n"
+ "concept C = requires C2<T>;");
+
+ verifyNoCrash("template <typename T>\n"
+ "concept C = 5 + 4;");
+
+ verifyNoCrash("template <typename T>\n"
+ "concept C = class X;");
+
+ verifyNoCrash("template <typename T>\n"
+ "concept C = [] && true;");
+
+ verifyNoCrash("template <typename T>\n"
+ "concept C = [] && requires(T t) { typename T::size_type; };");
+}
+
+TEST_F(FormatTest, RequiresClausesPositions) {
+ auto Style = getLLVMStyle();
+ EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
+ EXPECT_EQ(Style.IndentRequiresClause, true);
+
+ // The default in LLVM style is REI_OuterScope, but these tests were written
+ // when the default was REI_Keyword.
+ Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "struct Bar;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "class Bar {\n"
+ "public:\n"
+ " Bar(T t);\n"
+ " bool baz();\n"
+ "};",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ " requires requires(T &&t) {\n"
+ " typename T::I;\n"
+ " requires(F<typename T::I> && std::trait<typename T::I>);\n"
+ " }\n"
+ "Bar(T) -> Bar<typename T::I>;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "constexpr T MyGlobal;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.baz() } -> std::same_as<bool>;\n"
+ " requires std::same_as<T::Factor, int>;\n"
+ " }\n"
+ "inline int bar(T t) {\n"
+ " return t.baz() ? T::Factor : 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "inline int bar(T t)\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.baz() } -> std::same_as<bool>;\n"
+ " requires std::same_as<T::Factor, int>;\n"
+ " }\n"
+ "{\n"
+ " return t.baz() ? T::Factor : 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires F<T>\n"
+ "int bar(T t) {\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ " requires F<T>\n"
+ "{\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int S::bar(T t) &&\n"
+ " requires F<T>\n"
+ "{\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ " requires F<T>;",
+ Style);
+
+ Style.IndentRequiresClause = false;
+ verifyFormat("template <typename T>\n"
+ "requires F<T>\n"
+ "int bar(T t) {\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int S::bar(T t) &&\n"
+ "requires F<T>\n"
+ "{\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ "requires F<T>\n"
+ "{\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ Style.RequiresClausePosition = FormatStyle::RCPS_OwnLineWithBrace;
+ Style.IndentRequiresClause = true;
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "struct Bar;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "class Bar {\n"
+ "public:\n"
+ " Bar(T t);\n"
+ " bool baz();\n"
+ "};",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ " requires requires(T &&t) {\n"
+ " typename T::I;\n"
+ " requires(F<typename T::I> && std::trait<typename T::I>);\n"
+ " }\n"
+ "Bar(T) -> Bar<typename T::I>;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires(Foo<T> && std::trait<T>)\n"
+ "constexpr T MyGlobal;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.baz() } -> std::same_as<bool>;\n"
+ " requires std::same_as<T::Factor, int>;\n"
+ " }\n"
+ "inline int bar(T t) {\n"
+ " return t.baz() ? T::Factor : 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "inline int bar(T t)\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.baz() } -> std::same_as<bool>;\n"
+ " requires std::same_as<T::Factor, int>;\n"
+ " } {\n"
+ " return t.baz() ? T::Factor : 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires F<T>\n"
+ "int bar(T t) {\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ " requires F<T> {\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int S::bar(T t) &&\n"
+ " requires F<T> {\n"
+ " return 5;\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ " requires F<T>;",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "int bar(T t)\n"
+ " requires F<T> {}",
+ Style);
+
+ Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
+ Style.IndentRequiresClause = false;
+ verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
+ "template <typename T> requires Foo<T> void bar() {}\n"
+ "template <typename T> void bar() requires Foo<T> {}\n"
+ "template <typename T> void bar() requires Foo<T>;\n"
+ "template <typename T> void S::bar() && requires Foo<T> {}\n"
+ "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
+ Style);
+
+ auto ColumnStyle = Style;
+ ColumnStyle.ColumnLimit = 40;
+ verifyFormat("template <typename AAAAAAA>\n"
+ "requires Foo<T> struct Bar {};\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<T> void bar() {}\n"
+ "template <typename AAAAAAA>\n"
+ "void bar() requires Foo<T> {}\n"
+ "template <typename T>\n"
+ "void S::bar() && requires Foo<T> {}\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<T> Baz(T) -> Baz<T>;",
+ ColumnStyle);
+
+ verifyFormat("template <typename T>\n"
+ "requires Foo<AAAAAAA> struct Bar {};\n"
+ "template <typename T>\n"
+ "requires Foo<AAAAAAA> void bar() {}\n"
+ "template <typename T>\n"
+ "void bar() requires Foo<AAAAAAA> {}\n"
+ "template <typename T>\n"
+ "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
+ ColumnStyle);
+
+ verifyFormat("template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "struct Bar {};\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "void bar() {}\n"
+ "template <typename AAAAAAA>\n"
+ "void bar()\n"
+ " requires Foo<AAAAAAAAAAAAAAAA> {}\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "Bar(T) -> Bar<T>;",
+ ColumnStyle);
+
+ Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
+ ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
+
+ verifyFormat("template <typename T>\n"
+ "requires Foo<T> struct Bar {};\n"
+ "template <typename T>\n"
+ "requires Foo<T> void bar() {}\n"
+ "template <typename T>\n"
+ "void bar()\n"
+ "requires Foo<T> {}\n"
+ "template <typename T>\n"
+ "void bar()\n"
+ "requires Foo<T>;\n"
+ "template <typename T>\n"
+ "void S::bar() &&\n"
+ "requires Foo<T> {}\n"
+ "template <typename T>\n"
+ "requires Foo<T> Bar(T) -> Bar<T>;",
+ Style);
+
+ verifyFormat("template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "struct Bar {};\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "void bar() {}\n"
+ "template <typename AAAAAAA>\n"
+ "void bar()\n"
+ "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "Bar(T) -> Bar<T>;",
+ ColumnStyle);
+
+ Style.IndentRequiresClause = true;
+ ColumnStyle.IndentRequiresClause = true;
+
+ verifyFormat("template <typename T>\n"
+ " requires Foo<T> struct Bar {};\n"
+ "template <typename T>\n"
+ " requires Foo<T> void bar() {}\n"
+ "template <typename T>\n"
+ "void bar()\n"
+ " requires Foo<T> {}\n"
+ "template <typename T>\n"
+ "void S::bar() &&\n"
+ " requires Foo<T> {}\n"
+ "template <typename T>\n"
+ " requires Foo<T> Bar(T) -> Bar<T>;",
+ Style);
+
+ verifyFormat("template <typename AAAAAAA>\n"
+ " requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "struct Bar {};\n"
+ "template <typename AAAAAAA>\n"
+ " requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "void bar() {}\n"
+ "template <typename AAAAAAA>\n"
+ "void bar()\n"
+ " requires Foo<AAAAAAAAAAAAAAAA> {}\n"
+ "template <typename AAAAAAA>\n"
+ " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
+ "template <typename AAAAAAA>\n"
+ " requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "Bar(T) -> Bar<T>;",
+ ColumnStyle);
+
+ Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
+ ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
+
+ verifyFormat("template <typename T> requires Foo<T>\n"
+ "struct Bar {};\n"
+ "template <typename T> requires Foo<T>\n"
+ "void bar() {}\n"
+ "template <typename T>\n"
+ "void bar() requires Foo<T>\n"
+ "{}\n"
+ "template <typename T> void bar() requires Foo<T>;\n"
+ "template <typename T>\n"
+ "void S::bar() && requires Foo<T>\n"
+ "{}\n"
+ "template <typename T> requires Foo<T>\n"
+ "Bar(T) -> Bar<T>;",
+ Style);
+
+ verifyFormat("template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "struct Bar {};\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "void bar() {}\n"
+ "template <typename AAAAAAA>\n"
+ "void bar()\n"
+ " requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "{}\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAA>\n"
+ "Bar(T) -> Bar<T>;\n"
+ "template <typename AAAAAAA>\n"
+ "requires Foo<AAAAAAAAAAAAAAAA>\n"
+ "Bar(T) -> Bar<T>;",
+ ColumnStyle);
+}
+
+TEST_F(FormatTest, RequiresClauses) {
+ verifyFormat("struct [[nodiscard]] zero_t {\n"
+ " template <class T>\n"
+ " requires requires { number_zero_v<T>; }\n"
+ " [[nodiscard]] constexpr operator T() const {\n"
+ " return number_zero_v<T>;\n"
+ " }\n"
+ "};");
+
+ verifyFormat("template <class T>\n"
+ " requires(std::same_as<int, T>)\n"
+ "decltype(auto) fun() {}");
+
+ auto Style = getLLVMStyle();
+
+ verifyFormat(
+ "template <typename T>\n"
+ " requires is_default_constructible_v<hash<T>> and\n"
+ " is_copy_constructible_v<hash<T>> and\n"
+ " is_move_constructible_v<hash<T>> and\n"
+ " is_copy_assignable_v<hash<T>> and "
+ "is_move_assignable_v<hash<T>> and\n"
+ " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
+ " is_callable_v<hash<T>(T)> and\n"
+ " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
+ " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
+ " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
+ "struct S {};",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat(
+ "template <typename T>\n"
+ " requires is_default_constructible_v<hash<T>>\n"
+ " and is_copy_constructible_v<hash<T>>\n"
+ " and is_move_constructible_v<hash<T>>\n"
+ " and is_copy_assignable_v<hash<T>> and "
+ "is_move_assignable_v<hash<T>>\n"
+ " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
+ " and is_callable_v<hash<T>(T)>\n"
+ " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
+ " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
+ " and is_same_v<size_t, decltype(hash<T>(declval<const T "
+ "&>()))>\n"
+ "struct S {};",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.ConstructorInitializerIndentWidth = 4;
+ Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
+ Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
+ verifyFormat("constexpr Foo(Foo const &other)\n"
+ " requires std::is_copy_constructible<T>\n"
+ " : value{other.value} {\n"
+ " do_magic();\n"
+ " do_more_magic();\n"
+ "}",
+ Style);
+
+ // Not a clause, but we once hit an assert.
+ verifyFormat("#if 0\n"
+ "#else\n"
+ "foo();\n"
+ "#endif\n"
+ "bar(requires);");
+
+ verifyNoCrash("template <class T>\n"
+ " requires(requires { std::declval<T>()");
+}
+
+TEST_F(FormatTest, RequiresExpressionIndentation) {
+ auto Style = getLLVMStyle();
+ EXPECT_EQ(Style.RequiresExpressionIndentation, FormatStyle::REI_OuterScope);
+
+ verifyFormat("template <typename T>\n"
+ "concept C = requires(T t) {\n"
+ " typename T::value;\n"
+ " requires requires(typename T::value v) {\n"
+ " { t == v } -> std::same_as<bool>;\n"
+ " };\n"
+ "};",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ "void bar(T)\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.foo() } -> std::same_as<int>;\n"
+ " } && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " --t;\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires Foo<T> &&\n"
+ " requires(T t) {\n"
+ " { t.foo() } -> std::same_as<int>;\n"
+ " } && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " --t;\n"
+ " }\n"
+ "void bar(T);",
+ Style);
+
+ verifyFormat("template <typename T> void f() {\n"
+ " if constexpr (requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " }) {\n"
+ " }\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T> void f() {\n"
+ " if constexpr (condition && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " }) {\n"
+ " }\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T> struct C {\n"
+ " void f()\n"
+ " requires requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " };\n"
+ "};",
+ Style);
+
+ Style.RequiresExpressionIndentation = FormatStyle::REI_Keyword;
+
+ verifyFormat("template <typename T>\n"
+ "concept C = requires(T t) {\n"
+ " typename T::value;\n"
+ " requires requires(typename T::value v) {\n"
+ " { t == v } -> std::same_as<bool>;\n"
+ " };\n"
+ " };",
+ Style);
+
+ verifyFormat(
+ "template <typename T>\n"
+ "void bar(T)\n"
+ " requires Foo<T> && requires(T t) {\n"
+ " { t.foo() } -> std::same_as<int>;\n"
+ " } && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " --t;\n"
+ " };",
+ Style);
+
+ verifyFormat("template <typename T>\n"
+ " requires Foo<T> &&\n"
+ " requires(T t) {\n"
+ " { t.foo() } -> std::same_as<int>;\n"
+ " } && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " --t;\n"
+ " }\n"
+ "void bar(T);",
+ Style);
+
+ verifyFormat("template <typename T> void f() {\n"
+ " if constexpr (requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " }) {\n"
+ " }\n"
+ "}",
+ Style);
+
+ verifyFormat(
+ "template <typename T> void f() {\n"
+ " if constexpr (condition && requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " }) {\n"
+ " }\n"
+ "}",
+ Style);
+
+ verifyFormat("template <typename T> struct C {\n"
+ " void f()\n"
+ " requires requires(T t) {\n"
+ " { t.bar() } -> std::same_as<bool>;\n"
+ " };\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, StatementAttributeLikeMacros) {
+ FormatStyle Style = getLLVMStyle();
+ StringRef Source = "void Foo::slot() {\n"
+ " unsigned char MyChar = 'x';\n"
+ " emit signal(MyChar);\n"
+ " Q_EMIT signal(MyChar);\n"
+ "}";
+
+ verifyFormat(Source, Style);
+
+ Style.AlignConsecutiveDeclarations.Enabled = true;
+ verifyFormat("void Foo::slot() {\n"
+ " unsigned char MyChar = 'x';\n"
+ " emit signal(MyChar);\n"
+ " Q_EMIT signal(MyChar);\n"
+ "}",
+ Source, Style);
+
+ Style.StatementAttributeLikeMacros.push_back("emit");
+ verifyFormat(Source, Style);
+
+ Style.StatementAttributeLikeMacros = {};
+ verifyFormat("void Foo::slot() {\n"
+ " unsigned char MyChar = 'x';\n"
+ " emit signal(MyChar);\n"
+ " Q_EMIT signal(MyChar);\n"
+ "}",
+ Source, Style);
+}
+
+TEST_F(FormatTest, IndentAccessModifiers) {
+ FormatStyle Style = getLLVMStyle();
+ Style.IndentAccessModifiers = true;
+ // Members are *two* levels below the record;
+ // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
+ verifyFormat("class C {\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("union C {\n"
+ " int i;\n"
+ " unsigned u;\n"
+ "};",
+ Style);
+ // Access modifiers should be indented one level below the record.
+ verifyFormat("class C {\n"
+ " public:\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("class C {\n"
+ " public /* comment */:\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("struct S {\n"
+ " private:\n"
+ " class C {\n"
+ " int j;\n"
+ "\n"
+ " public:\n"
+ " C();\n"
+ " };\n"
+ "\n"
+ " public:\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
+ verifyFormat("struct S\n"
+ " {\n"
+ " public:\n"
+ " int i;\n"
+ "\n"
+ " private:\n"
+ " class C\n"
+ " {\n"
+ " private:\n"
+ " int j;\n"
+ " };\n"
+ " };",
+ Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Attach;
+ // Enumerations are not records and should be unaffected.
+ Style.AllowShortEnumsOnASingleLine = false;
+ verifyFormat("enum class E {\n"
+ " A,\n"
+ " B\n"
+ "};",
+ Style);
+ // Test with a different indentation width;
+ // also proves that the result is Style.AccessModifierOffset agnostic.
+ Style.IndentWidth = 3;
+ verifyFormat("class C {\n"
+ " public:\n"
+ " int i;\n"
+ "};",
+ Style);
+ verifyFormat("class C {\n"
+ " public /**/:\n"
+ " int i;\n"
+ "};",
+ Style);
+ Style.AttributeMacros.push_back("FOO");
+ verifyFormat("class C {\n"
+ " FOO public:\n"
+ " int i;\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, LimitlessStringsAndComments) {
+ auto Style = getLLVMStyleWithColumns(0);
+ constexpr StringRef Code(
+ "/**\n"
+ " * This is a multiline comment with quite some long lines, at least for "
+ "the LLVM Style.\n"
+ " * We will redo this with strings and line comments. Just to check if "
+ "everything is working.\n"
+ " */\n"
+ "bool foo() {\n"
+ " /* Single line multi line comment. */\n"
+ " const std::string String = \"This is a multiline string with quite "
+ "some long lines, at least for the LLVM Style.\"\n"
+ " \"We already did it with multi line "
+ "comments, and we will do it with line comments. Just to check if "
+ "everything is working.\";\n"
+ " // This is a line comment (block) with quite some long lines, at "
+ "least for the LLVM Style.\n"
+ " // We already did this with multi line comments and strings. Just to "
+ "check if everything is working.\n"
+ " const std::string SmallString = \"Hello World\";\n"
+ " // Small line comment\n"
+ " return String.size() > SmallString.size();\n"
+ "}");
+ verifyNoChange(Code, Style);
+}
+
+TEST_F(FormatTest, FormatDecayCopy) {
+ // error cases from unit tests
+ verifyFormat("foo(auto())");
+ verifyFormat("foo(auto{})");
+ verifyFormat("foo(auto({}))");
+ verifyFormat("foo(auto{{}})");
+
+ verifyFormat("foo(auto(1))");
+ verifyFormat("foo(auto{1})");
+ verifyFormat("foo(new auto(1))");
+ verifyFormat("foo(new auto{1})");
+ verifyFormat("decltype(auto(1)) x;");
+ verifyFormat("decltype(auto{1}) x;");
+ verifyFormat("auto(x);");
+ verifyFormat("auto{x};");
+ verifyFormat("new auto{x};");
+ verifyFormat("auto{x} = y;");
+ verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
+ // the user's own fault
+ verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
+ // clearly the user's own fault
+ verifyFormat("auto (*p)() = f;");
+}
+
+TEST_F(FormatTest, Cpp20ModulesSupport) {
+ FormatStyle Style = getLLVMStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+
+ verifyFormat("export import foo;", Style);
+ verifyFormat("export import foo:bar;", Style);
+ verifyFormat("export import foo.bar;", Style);
+ verifyFormat("export import foo.bar:baz;", Style);
+ verifyFormat("export import :bar;", Style);
+ verifyFormat("export module foo:bar;", Style);
+ verifyFormat("export module foo;", Style);
+ verifyFormat("export module foo.bar;", Style);
+ verifyFormat("export module foo.bar:baz;", Style);
+ verifyFormat("export import <string_view>;", Style);
+ verifyFormat("export import <Foo/Bar>;", Style);
+
+ verifyFormat("export type_name var;", Style);
+ verifyFormat("template <class T> export using A = B<T>;", Style);
+ verifyFormat("export using A = B;", Style);
+ verifyFormat("export int func() {\n"
+ " foo();\n"
+ "}",
+ Style);
+ verifyFormat("export struct {\n"
+ " int foo;\n"
+ "};",
+ Style);
+ verifyFormat("export {\n"
+ " int foo;\n"
+ "};",
+ Style);
+ verifyFormat("export export char const *hello() { return \"hello\"; }");
+
+ verifyFormat("import bar;", Style);
+ verifyFormat("import foo.bar;", Style);
+ verifyFormat("import foo:bar;", Style);
+ verifyFormat("import :bar;", Style);
+ verifyFormat("import /* module partition */ :bar;", Style);
+ verifyFormat("import <ctime>;", Style);
+ verifyFormat("import \"header\";", Style);
+
+ verifyFormat("module foo;", Style);
+ verifyFormat("module foo:bar;", Style);
+ verifyFormat("module foo.bar;", Style);
+ verifyFormat("module;", Style);
+
+ verifyFormat("export namespace hi {\n"
+ "const char *sayhi();\n"
+ "}",
+ Style);
+
+ verifyFormat("module :private;", Style);
+ verifyFormat("import <foo/bar.h>;", Style);
+ verifyFormat("import foo...bar;", Style);
+ verifyFormat("import ..........;", Style);
+ verifyFormat("module foo:private;", Style);
+ verifyFormat("import a", Style);
+ verifyFormat("module a", Style);
+ verifyFormat("export import a", Style);
+ verifyFormat("export module a", Style);
+
+ verifyFormat("import", Style);
+ verifyFormat("module", Style);
+ verifyFormat("export", Style);
+
+ verifyFormat("import /* not keyword */ = val ? 2 : 1;");
+ verifyFormat("_world->import<engine_module>();");
+}
+
+TEST_F(FormatTest, CoroutineForCoawait) {
+ FormatStyle Style = getLLVMStyle();
+ verifyFormat("for co_await (auto x : range())\n ;");
+ verifyFormat("for (auto i : arr) {\n"
+ "}",
+ Style);
+ verifyFormat("for co_await (auto i : arr) {\n"
+ "}",
+ Style);
+ verifyFormat("for co_await (auto i : foo(T{})) {\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, CoroutineCoAwait) {
+ verifyFormat("int x = co_await foo();");
+ verifyFormat("int x = (co_await foo());");
+ verifyFormat("co_await (42);");
+ verifyFormat("void operator co_await(int);");
+ verifyFormat("void operator co_await(a);");
+ verifyFormat("co_await a;");
+ verifyFormat("co_await missing_await_resume{};");
+ verifyFormat("co_await a; // comment");
+ verifyFormat("void test0() { co_await a; }");
+ verifyFormat("co_await co_await co_await foo();");
+ verifyFormat("co_await foo().bar();");
+ verifyFormat("co_await [this]() -> Task { co_return x; }");
+ verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
+ "foo(); }(x, y);");
+
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ verifyFormat("co_await [this](int a, int b) -> Task {\n"
+ " co_return co_await foo();\n"
+ "}(x, y);",
+ Style);
+ verifyFormat("co_await;");
+}
+
+TEST_F(FormatTest, CoroutineCoYield) {
+ verifyFormat("int x = co_yield foo();");
+ verifyFormat("int x = (co_yield foo());");
+ verifyFormat("co_yield (42);");
+ verifyFormat("co_yield {42};");
+ verifyFormat("co_yield 42;");
+ verifyFormat("co_yield n++;");
+ verifyFormat("co_yield ++n;");
+ verifyFormat("co_yield;");
+}
+
+TEST_F(FormatTest, CoroutineCoReturn) {
+ verifyFormat("co_return (42);");
+ verifyFormat("co_return;");
+ verifyFormat("co_return {};");
+ verifyFormat("co_return x;");
+ verifyFormat("co_return co_await foo();");
+ verifyFormat("co_return co_yield foo();");
+}
+
+TEST_F(FormatTest, EmptyShortBlock) {
+ auto Style = getLLVMStyle();
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
+
+ verifyFormat("try {\n"
+ " doA();\n"
+ "} catch (Exception &e) {\n"
+ " e.printStackTrace();\n"
+ "}",
+ Style);
+
+ verifyFormat("try {\n"
+ " doA();\n"
+ "} catch (Exception &e) {}",
+ Style);
+}
+
+TEST_F(FormatTest, ShortTemplatedArgumentLists) {
+ auto Style = getLLVMStyle();
+
+ verifyFormat("template <> struct S : Template<int (*)[]> {};", Style);
+ verifyFormat("template <> struct S : Template<int (*)[10]> {};", Style);
+ verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
+ verifyFormat("struct Y<[] { return 0; }> {};", Style);
+
+ verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
+ verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
+}
+
+TEST_F(FormatTest, MultilineLambdaInConditional) {
+ auto Style = getLLVMStyleWithColumns(70);
+ verifyFormat("auto aLengthyIdentifier = oneExpressionSoThatWeBreak ? []() {\n"
+ " ;\n"
+ " return 5;\n"
+ "}()\n"
+ " : 2;",
+ Style);
+ verifyFormat(
+ "auto aLengthyIdentifier = oneExpressionSoThatWeBreak ? 2 : []() {\n"
+ " ;\n"
+ " return 5;\n"
+ "}();",
+ Style);
+
+ Style = getLLVMStyleWithColumns(60);
+ verifyFormat("auto aLengthyIdentifier = oneExpressionSoThatWeBreak\n"
+ " ? []() {\n"
+ " ;\n"
+ " return 5;\n"
+ " }()\n"
+ " : 2;",
+ Style);
+ verifyFormat("auto aLengthyIdentifier =\n"
+ " oneExpressionSoThatWeBreak ? 2 : []() {\n"
+ " ;\n"
+ " return 5;\n"
+ " }();",
+ Style);
+
+ Style = getLLVMStyleWithColumns(40);
+ verifyFormat("auto aLengthyIdentifier =\n"
+ " oneExpressionSoThatWeBreak ? []() {\n"
+ " ;\n"
+ " return 5;\n"
+ " }()\n"
+ " : 2;",
+ Style);
+ verifyFormat("auto aLengthyIdentifier =\n"
+ " oneExpressionSoThatWeBreak\n"
+ " ? 2\n"
+ " : []() {\n"
+ " ;\n"
+ " return 5;\n"
+ " };",
+ Style);
+}
+
+TEST_F(FormatTest, UnderstandsDigraphs) {
+ verifyFormat("int arr<:5:> = {};");
+ verifyFormat("int arr[5] = <%%>;");
+ verifyFormat("int arr<:::qualified_variable:> = {};");
+ verifyFormat("int arr[::qualified_variable] = <%%>;");
+ verifyFormat("%:include <header>");
+ verifyFormat("%:define A x##y");
+ verifyFormat("#define A x%:%:y");
+}
+
+TEST_F(FormatTest, FormatsVariableTemplates) {
+ verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
+ verifyFormat("template <typename T> "
+ "inline bool var = is_integral_v<T> && is_signed_v<T>;");
+}
+
+TEST_F(FormatTest, RemoveSemicolon) {
+ FormatStyle Style = getLLVMStyle();
+ Style.RemoveSemicolon = true;
+
+ verifyFormat("int max(int a, int b) { return a > b ? a : b; }",
+ "int max(int a, int b) { return a > b ? a : b; };", Style);
+
+ verifyFormat("int max(int a, int b) { return a > b ? a : b; }",
+ "int max(int a, int b) { return a > b ? a : b; };;", Style);
+
+ verifyFormat("class Foo {\n"
+ " int getSomething() const { return something; }\n"
+ "};",
+ "class Foo {\n"
+ " int getSomething() const { return something; };\n"
+ "};",
+ Style);
+
+ verifyFormat("class Foo {\n"
+ " int getSomething() const { return something; }\n"
+ "};",
+ "class Foo {\n"
+ " int getSomething() const { return something; };;\n"
+ "};",
+ Style);
+
+ verifyFormat("for (;;) {\n"
+ "}",
+ Style);
+
+ verifyFormat("class [[deprecated(\"\")]] C {\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ verifyFormat("struct EXPORT_MACRO [[nodiscard]] C {\n"
+ " int i;\n"
+ "};",
+ Style);
+
+ verifyIncompleteFormat("class C final [[deprecated(l]] {});", Style);
+
+ verifyFormat("void main() {}", "void main() {};", Style);
+
+ verifyFormat("struct Foo {\n"
+ " Foo() {}\n"
+ " ~Foo() {}\n"
+ "};",
+ "struct Foo {\n"
+ " Foo() {};\n"
+ " ~Foo() {};\n"
+ "};",
+ Style);
+
+// We can't (and probably shouldn't) support the following.
+#if 0
+ verifyFormat("void foo() {} //\n"
+ "int bar;",
+ "void foo() {}; //\n"
+ "; int bar;",
+ Style);
+#endif
+
+ verifyFormat("auto sgf = [] {\n"
+ " ogl = {\n"
+ " a, b, c, d, e,\n"
+ " };\n"
+ "};",
+ Style);
+
+ Style.TypenameMacros.push_back("STRUCT");
+ verifyFormat("STRUCT(T, B) { int i; };", Style);
+}
+
+TEST_F(FormatTest, EnumTrailingComma) {
+ constexpr StringRef Code("enum : int { /**/ };\n"
+ "enum {\n"
+ " a,\n"
+ " b,\n"
+ " c, //\n"
+ "};\n"
+ "enum Color { red, green, blue /**/ };");
+ verifyFormat(Code);
+
+ auto Style = getLLVMStyle();
+ Style.EnumTrailingComma = FormatStyle::ETC_Insert;
+ verifyFormat("enum : int { /**/ };\n"
+ "enum {\n"
+ " a,\n"
+ " b,\n"
+ " c, //\n"
+ "};\n"
+ "enum Color { red, green, blue, /**/ };",
+ Code, Style);
+
+ Style.EnumTrailingComma = FormatStyle::ETC_Remove;
+ verifyFormat("enum : int { /**/ };\n"
+ "enum {\n"
+ " a,\n"
+ " b,\n"
+ " c //\n"
+ "};\n"
+ "enum Color { red, green, blue /**/ };",
+ Code, Style);
+
+ EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
+ Style.AllowShortEnumsOnASingleLine = false;
+
+ constexpr StringRef Input("enum {\n"
+ " //\n"
+ " a,\n"
+ " /**/\n"
+ " b,\n"
+ "};");
+ verifyFormat(Input, Input, Style, {tooling::Range(12, 3)}); // line 3
+ verifyFormat("enum {\n"
+ " //\n"
+ " a,\n"
+ " /**/\n"
+ " b\n"
+ "};",
+ Input, Style, {tooling::Range(24, 3)}); // line 5
+
+ Style.EnumTrailingComma = FormatStyle::ETC_Insert;
+ verifyFormat("enum class MyEnum_E {\n"
+ " MY_ENUM = 0U,\n"
+ "};",
+ "enum class MyEnum_E {\n"
+ " MY_ENUM = 0U\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, BreakAfterAttributes) {
+ constexpr StringRef Code("[[maybe_unused]] const int i;\n"
+ "[[foo([[]])]] [[maybe_unused]]\n"
+ "int j;\n"
+ "[[maybe_unused]]\n"
+ "foo<int> k;\n"
+ "[[nodiscard]] inline int f(int &i);\n"
+ "[[foo([[]])]] [[nodiscard]]\n"
+ "int g(int &i);\n"
+ "[[nodiscard]]\n"
+ "inline int f(int &i) {\n"
+ " i = 1;\n"
+ " return 0;\n"
+ "}\n"
+ "[[foo([[]])]] [[nodiscard]] int g(int &i) {\n"
+ " i = 0;\n"
+ " return 1;\n"
+ "}");
+
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.BreakAfterAttributes, FormatStyle::ABS_Leave);
+ verifyNoChange(Code, Style);
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_LeaveAll;
+ verifyNoChange("[[deprecated(\"Don't use this version\")]]\n"
+ "[[nodiscard]]\n"
+ "bool foo() {\n"
+ " return true;\n"
+ "}\n"
+ "\n"
+ "[[deprecated(\"Don't use this version\")]]\n"
+ "[[nodiscard]] bool bar() {\n"
+ " return true;\n"
+ "}",
+ Style);
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_Never;
+ verifyFormat("[[maybe_unused]] const int i;\n"
+ "[[foo([[]])]] [[maybe_unused]] int j;\n"
+ "[[maybe_unused]] foo<int> k;\n"
+ "[[nodiscard]] inline int f(int &i);\n"
+ "[[foo([[]])]] [[nodiscard]] int g(int &i);\n"
+ "[[nodiscard]] inline int f(int &i) {\n"
+ " i = 1;\n"
+ " return 0;\n"
+ "}\n"
+ "[[foo([[]])]] [[nodiscard]] int g(int &i) {\n"
+ " i = 0;\n"
+ " return 1;\n"
+ "}",
+ Code, Style);
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_Always;
+ verifyFormat("[[maybe_unused]]\n"
+ "const int i;\n"
+ "[[foo([[]])]] [[maybe_unused]]\n"
+ "int j;\n"
+ "[[maybe_unused]]\n"
+ "foo<int> k;\n"
+ "[[nodiscard]]\n"
+ "inline int f(int &i);\n"
+ "[[foo([[]])]] [[nodiscard]]\n"
+ "int g(int &i);\n"
+ "[[nodiscard]]\n"
+ "inline int f(int &i) {\n"
+ " i = 1;\n"
+ " return 0;\n"
+ "}\n"
+ "[[foo([[]])]] [[nodiscard]]\n"
+ "int g(int &i) {\n"
+ " i = 0;\n"
+ " return 1;\n"
+ "}",
+ Code, Style);
+
+ constexpr StringRef CtrlStmtCode("[[likely]] if (a)\n"
+ " f();\n"
+ "else\n"
+ " g();\n"
+ "[[foo([[]])]]\n"
+ "switch (b) {\n"
+ "[[unlikely]] case 1:\n"
+ " ++b;\n"
+ " break;\n"
+ "[[likely]]\n"
+ "default:\n"
+ " return;\n"
+ "}\n"
+ "[[unlikely]] for (; c > 0; --c)\n"
+ " h();\n"
+ "[[likely]]\n"
+ "while (d > 0)\n"
+ " --d;");
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_Leave;
+ verifyNoChange(CtrlStmtCode, Style);
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_Never;
+ verifyFormat("[[likely]] if (a)\n"
+ " f();\n"
+ "else\n"
+ " g();\n"
+ "[[foo([[]])]] switch (b) {\n"
+ "[[unlikely]] case 1:\n"
+ " ++b;\n"
+ " break;\n"
+ "[[likely]] default:\n"
+ " return;\n"
+ "}\n"
+ "[[unlikely]] for (; c > 0; --c)\n"
+ " h();\n"
+ "[[likely]] while (d > 0)\n"
+ " --d;",
+ CtrlStmtCode, Style);
+
+ Style.BreakAfterAttributes = FormatStyle::ABS_Always;
+ verifyFormat("[[likely]]\n"
+ "if (a)\n"
+ " f();\n"
+ "else\n"
+ " g();\n"
+ "[[foo([[]])]]\n"
+ "switch (b) {\n"
+ "[[unlikely]]\n"
+ "case 1:\n"
+ " ++b;\n"
+ " break;\n"
+ "[[likely]]\n"
+ "default:\n"
+ " return;\n"
+ "}\n"
+ "[[unlikely]]\n"
+ "for (; c > 0; --c)\n"
+ " h();\n"
+ "[[likely]]\n"
+ "while (d > 0)\n"
+ " --d;",
+ CtrlStmtCode, Style);
+
+ verifyFormat("[[nodiscard]]\n"
+ "operator bool();\n"
+ "[[nodiscard]]\n"
+ "operator bool() {\n"
+ " return true;\n"
+ "}",
+ "[[nodiscard]] operator bool();\n"
+ "[[nodiscard]] operator bool() { return true; }",
+ Style);
+
+ constexpr StringRef CtorDtorCode("struct Foo {\n"
+ " [[deprecated]] Foo();\n"
+ " [[deprecated]] Foo() {}\n"
+ " [[deprecated]] ~Foo();\n"
+ " [[deprecated]] ~Foo() {}\n"
+ " [[deprecated]] void f();\n"
+ " [[deprecated]] void f() {}\n"
+ "};\n"
+ "[[deprecated]] Bar::Bar() {}\n"
+ "[[deprecated]] Bar::~Bar() {}\n"
+ "[[deprecated]] void g() {}");
+ verifyFormat("struct Foo {\n"
+ " [[deprecated]]\n"
+ " Foo();\n"
+ " [[deprecated]]\n"
+ " Foo() {}\n"
+ " [[deprecated]]\n"
+ " ~Foo();\n"
+ " [[deprecated]]\n"
+ " ~Foo() {}\n"
+ " [[deprecated]]\n"
+ " void f();\n"
+ " [[deprecated]]\n"
+ " void f() {}\n"
+ "};\n"
+ "[[deprecated]]\n"
+ "Bar::Bar() {}\n"
+ "[[deprecated]]\n"
+ "Bar::~Bar() {}\n"
+ "[[deprecated]]\n"
+ "void g() {}",
+ CtorDtorCode, Style);
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Linux;
+ verifyFormat("struct Foo {\n"
+ " [[deprecated]]\n"
+ " Foo();\n"
+ " [[deprecated]]\n"
+ " Foo()\n"
+ " {\n"
+ " }\n"
+ " [[deprecated]]\n"
+ " ~Foo();\n"
+ " [[deprecated]]\n"
+ " ~Foo()\n"
+ " {\n"
+ " }\n"
+ " [[deprecated]]\n"
+ " void f();\n"
+ " [[deprecated]]\n"
+ " void f()\n"
+ " {\n"
+ " }\n"
+ "};\n"
+ "[[deprecated]]\n"
+ "Bar::Bar()\n"
+ "{\n"
+ "}\n"
+ "[[deprecated]]\n"
+ "Bar::~Bar()\n"
+ "{\n"
+ "}\n"
+ "[[deprecated]]\n"
+ "void g()\n"
+ "{\n"
+ "}",
+ CtorDtorCode, Style);
+
+ verifyFormat("struct Foo {\n"
+ " [[maybe_unused]]\n"
+ " void operator+();\n"
+ "};\n"
+ "[[nodiscard]]\n"
+ "Foo &operator-(Foo &);",
+ Style);
+
+ Style.ReferenceAlignment = FormatStyle::RAS_Left;
+ verifyFormat("[[nodiscard]]\n"
+ "Foo& operator-(Foo&);",
+ Style);
+
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat("[[deprecated]]\n"
+ "void f() = delete;",
+ Style);
+}
+
+TEST_F(FormatTest, InsertNewlineAtEOF) {
+ FormatStyle Style = getLLVMStyle();
+ Style.InsertNewlineAtEOF = true;
+
+ verifyNoChange("int i;\n", Style);
+ verifyFormat("int i;\n", "int i;", Style);
+
+ constexpr StringRef Code("namespace {\n"
+ "int i;\n"
+ "} // namespace");
+ verifyFormat(Code.str() + '\n', Code, Style,
+ {tooling::Range(19, 13)}); // line 3
+}
+
+TEST_F(FormatTest, KeepEmptyLinesAtEOF) {
+ FormatStyle Style = getLLVMStyle();
+ Style.KeepEmptyLines.AtEndOfFile = true;
+
+ constexpr StringRef Code("int i;\n\n");
+ verifyNoChange(Code, Style);
+ verifyFormat(Code, "int i;\n\n\n", Style);
+}
+
+TEST_F(FormatTest, SpaceAfterUDL) {
+ verifyFormat("auto c = (4s).count();");
+ verifyFormat("auto x = 5s .count() == 5;");
+}
+
+TEST_F(FormatTest, InterfaceAsClassMemberName) {
+ verifyFormat("class Foo {\n"
+ " int interface;\n"
+ " Foo::Foo(int iface) : interface{iface} {}\n"
+ "}");
+}
+
+TEST_F(FormatTest, PreprocessorOverlappingRegions) {
+ verifyFormat("#ifdef\n\n"
+ "#else\n"
+ "#endif",
+ "#ifdef \n"
+ " \n"
+ "\n"
+ "#else \n"
+ "#endif ",
+ getGoogleStyle());
+}
+
+TEST_F(FormatTest, RemoveParentheses) {
+ FormatStyle Style = getLLVMStyle();
+ EXPECT_EQ(Style.RemoveParentheses, FormatStyle::RPS_Leave);
+
+ Style.RemoveParentheses = FormatStyle::RPS_MultipleParentheses;
+ verifyFormat("#define Foo(...) foo((__VA_ARGS__))", Style);
+ verifyFormat("int x __attribute__((aligned(16))) = 0;", Style);
+ verifyFormat("decltype((foo->bar)) baz;", Style);
+ verifyFormat("class __declspec(dllimport) X {};",
+ "class __declspec((dllimport)) X {};", Style);
+ verifyFormat("int x = (({ 0; }));", "int x = ((({ 0; })));", Style);
+ verifyFormat("while (a)\n"
+ " b;",
+ "while (((a)))\n"
+ " b;",
+ Style);
+ verifyFormat("while ((a = b))\n"
+ " c;",
+ "while (((a = b)))\n"
+ " c;",
+ Style);
+ verifyFormat("if (a)\n"
+ " b;",
+ "if (((a)))\n"
+ " b;",
+ Style);
+ verifyFormat("if constexpr ((a = b))\n"
+ " c;",
+ "if constexpr (((a = b)))\n"
+ " c;",
+ Style);
+ verifyFormat("if (({ a; }))\n"
+ " b;",
+ "if ((({ a; })))\n"
+ " b;",
+ Style);
+ verifyFormat("static_assert((std::is_constructible_v<T, Args &&> && ...));",
+ "static_assert(((std::is_constructible_v<T, Args &&> && ...)));",
+ Style);
+ verifyFormat("foo((a, b));", "foo(((a, b)));", Style);
+ verifyFormat("foo((a, b));", "foo(((a), b));", Style);
+ verifyFormat("foo((a, b));", "foo((a, (b)));", Style);
+ verifyFormat("foo((a, b, c));", "foo((a, ((b)), c));", Style);
+ verifyFormat("(..., (hash_a = hash_combine(hash_a, hash_b)));",
+ "(..., ((hash_a = hash_combine(hash_a, hash_b))));", Style);
+ verifyFormat("((hash_a = hash_combine(hash_a, hash_b)), ...);",
+ "(((hash_a = hash_combine(hash_a, hash_b))), ...);", Style);
+ verifyFormat("return (0);", "return (((0)));", Style);
+ verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style);
+ verifyFormat("return ((... && std::is_convertible_v<TArgsLocal, TArgs>));",
+ "return (((... && std::is_convertible_v<TArgsLocal, TArgs>)));",
+ Style);
+ verifyFormat("MOCK_METHOD(void, Function, (), override);",
+ "MOCK_METHOD(void, Function, (), (override));", Style);
+
+ Style.MacrosSkippedByRemoveParentheses.push_back("FOO");
+ verifyFormat("FOO((a && b));", Style);
+ verifyFormat("FOO((int), func, ((std::map<int, int>)), (override));", Style);
+
+ Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+ verifyFormat("#define Return0 return (0);", Style);
+ verifyFormat("return 0;", "return (0);", Style);
+ verifyFormat("co_return 0;", "co_return ((0));", Style);
+ verifyFormat("return 0;", "return (((0)));", Style);
+ verifyFormat("return ({ 0; });", "return ((({ 0; })));", Style);
+ verifyFormat("return (... && std::is_convertible_v<TArgsLocal, TArgs>);",
+ "return (((... && std::is_convertible_v<TArgsLocal, TArgs>)));",
+ Style);
+ verifyFormat("inline decltype(auto) f() {\n"
+ " if (a) {\n"
+ " return (a);\n"
+ " }\n"
+ " return (b);\n"
+ "}",
+ "inline decltype(auto) f() {\n"
+ " if (a) {\n"
+ " return ((a));\n"
+ " }\n"
+ " return ((b));\n"
+ "}",
+ Style);
+ verifyFormat("auto g() {\n"
+ " decltype(auto) x = [] {\n"
+ " auto y = [] {\n"
+ " if (a) {\n"
+ " return a;\n"
+ " }\n"
+ " return b;\n"
+ " };\n"
+ " if (c) {\n"
+ " return (c);\n"
+ " }\n"
+ " return (d);\n"
+ " };\n"
+ " if (e) {\n"
+ " return e;\n"
+ " }\n"
+ " return f;\n"
+ "}",
+ "auto g() {\n"
+ " decltype(auto) x = [] {\n"
+ " auto y = [] {\n"
+ " if (a) {\n"
+ " return ((a));\n"
+ " }\n"
+ " return ((b));\n"
+ " };\n"
+ " if (c) {\n"
+ " return ((c));\n"
+ " }\n"
+ " return ((d));\n"
+ " };\n"
+ " if (e) {\n"
+ " return ((e));\n"
+ " }\n"
+ " return ((f));\n"
+ "}",
+ Style);
+
+ Style.ColumnLimit = 25;
+ verifyFormat("return (a + b) - (c + d);",
+ "return (((a + b)) -\n"
+ " ((c + d)));",
+ Style);
+}
+
+TEST_F(FormatTest, AllowBreakBeforeNoexceptSpecifier) {
+ auto Style = getLLVMStyleWithColumns(35);
+
+ EXPECT_EQ(Style.AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
+ verifyFormat("void foo(int arg1,\n"
+ " double arg2) noexcept;",
+ Style);
+
+ // The following line does not fit within the 35 column limit, but that's what
+ // happens with no break allowed.
+ verifyFormat("void bar(int arg1, double arg2) noexcept(\n"
+ " noexcept(baz(arg1)) &&\n"
+ " noexcept(baz(arg2)));",
+ Style);
+
+ verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments() noexcept;",
+ Style);
+
+ Style.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Always;
+ verifyFormat("void foo(int arg1,\n"
+ " double arg2) noexcept;",
+ Style);
+
+ verifyFormat("void bar(int arg1, double arg2)\n"
+ " noexcept(noexcept(baz(arg1)) &&\n"
+ " noexcept(baz(arg2)));",
+ Style);
+
+ verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments()\n"
+ " noexcept;",
+ Style);
+
+ Style.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_OnlyWithParen;
+ verifyFormat("void foo(int arg1,\n"
+ " double arg2) noexcept;",
+ Style);
+
+ verifyFormat("void bar(int arg1, double arg2)\n"
+ " noexcept(noexcept(baz(arg1)) &&\n"
+ " noexcept(baz(arg2)));",
+ Style);
+
+ verifyFormat("void aVeryLongFunctionNameWithoutAnyArguments() noexcept;",
+ Style);
+}
+
+TEST_F(FormatTest, PPBranchesInBracedInit) {
+ verifyFormat("A a_{kFlag1,\n"
+ "#if BUILD_FLAG\n"
+ " kFlag2,\n"
+ "#else\n"
+ " kFlag3,\n"
+ "#endif\n"
+ " kFlag4};",
+ "A a_{\n"
+ " kFlag1,\n"
+ "#if BUILD_FLAG\n"
+ " kFlag2,\n"
+ "#else\n"
+ " kFlag3,\n"
+ "#endif\n"
+ " kFlag4\n"
+ "};");
+}
+
+TEST_F(FormatTest, PPDirectivesAndCommentsInBracedInit) {
+ verifyFormat("{\n"
+ " char *a[] = {\n"
+ " /* abc */ \"abc\",\n"
+ "#if FOO\n"
+ " /* xyz */ \"xyz\",\n"
+ "#endif\n"
+ " /* last */ \"last\"};\n"
+ "}",
+ getLLVMStyleWithColumns(30));
+}
+
+TEST_F(FormatTest, BreakAdjacentStringLiterals) {
+ constexpr StringRef Code(
+ "return \"Code\" \"\\0\\52\\26\\55\\55\\0\" \"x013\" \"\\02\\xBA\";");
+
+ verifyFormat("return \"Code\"\n"
+ " \"\\0\\52\\26\\55\\55\\0\"\n"
+ " \"x013\"\n"
+ " \"\\02\\xBA\";",
+ Code);
+
+ auto Style = getLLVMStyle();
+ Style.BreakAdjacentStringLiterals = false;
+ verifyFormat(Code, Style);
+}
+
+TEST_F(FormatTest, AlignUTFCommentsAndStringLiterals) {
+ verifyFormat(
+ "int rus; // А теперь комментарии, например, на русском, 2-байта\n"
+ "int long_rus; // Верхний коммент еще не превысил границу в 80, однако\n"
+ " // уже отодвинут. Перенос, при этом, отрабатывает верно");
+
+ auto Style = getLLVMStyle();
+ Style.ColumnLimit = 15;
+ verifyNoChange("#define test \\\n"
+ " /* 测试 */ \\\n"
+ " \"aa\" \\\n"
+ " \"bb\"",
+ Style);
+
+ Style.ColumnLimit = 25;
+ verifyFormat("struct foo {\n"
+ " int iiiiii; ///< iiiiii\n"
+ " int b; ///< ыыы\n"
+ " int c; ///< ыыыы\n"
+ "};",
+ Style);
+
+ Style.ColumnLimit = 35;
+ verifyFormat("#define SENSOR_DESC_1 \\\n"
+ " \"{\" \\\n"
+ " \"unit_of_measurement: \\\"°C\\\",\" \\\n"
+ " \"}\"",
+ Style);
+
+ Style.ColumnLimit = 80;
+ Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
+ verifyFormat("Languages languages = {\n"
+ " Language{{'e', 'n'}, U\"Test English\" },\n"
+ " Language{{'l', 'v'}, U\"Test Latviešu\"},\n"
+ " Language{{'r', 'u'}, U\"Test Русский\" },\n"
+ "};",
+ Style);
+}
+
+TEST_F(FormatTest, SpaceBetweenKeywordAndLiteral) {
+ verifyFormat("return .5;");
+ verifyFormat("return not '5';");
+ verifyFormat("return sizeof \"5\";");
+}
+
+TEST_F(FormatTest, BreakBinaryOperations) {
+ auto Style = getLLVMStyleWithColumns(60);
+ FormatStyle::BreakBinaryOperationsOptions ExpectedDefault = {
+ FormatStyle::BBO_Never, {}};
+ EXPECT_EQ(Style.BreakBinaryOperations, ExpectedDefault);
+
+ // Logical operations
+ verifyFormat("if (condition1 && condition2) {\n"
+ "}",
+ Style);
+
+ verifyFormat("if (condition1 && condition2 &&\n"
+ " (condition3 || condition4) && condition5 &&\n"
+ " condition6) {\n"
+ "}",
+ Style);
+
+ verifyFormat("if (loooooooooooooooooooooongcondition1 &&\n"
+ " loooooooooooooooooooooongcondition2) {\n"
+ "}",
+ Style);
+
+ // Arithmetic
+ verifyFormat("const int result = lhs + rhs;", Style);
+
+ verifyFormat("const int result = loooooooongop1 + looooooooongop2 +\n"
+ " loooooooooooooooooooooongop3;",
+ Style);
+
+ verifyFormat("result = longOperand1 + longOperand2 -\n"
+ " (longOperand3 + longOperand4) -\n"
+ " longOperand5 * longOperand6;",
+ Style);
+
+ verifyFormat("const int result =\n"
+ " operand1 + operand2 - (operand3 + operand4);",
+ Style);
+
+ // Check operator>> special case.
+ verifyFormat("std::cin >> longOperand_1 >> longOperand_2 >>\n"
+ " longOperand_3_;",
+ Style);
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_OnePerLine;
+
+ // Logical operations
+ verifyFormat("if (condition1 && condition2) {\n"
+ "}",
+ Style);
+
+ verifyFormat("if (condition1 && // comment\n"
+ " condition2 &&\n"
+ " (condition3 || condition4) && // comment\n"
+ " condition5 &&\n"
+ " condition6) {\n"
+ "}",
+ Style);
+
+ verifyFormat("if (loooooooooooooooooooooongcondition1 &&\n"
+ " loooooooooooooooooooooongcondition2) {\n"
+ "}",
+ Style);
+
+ // Arithmetic
+ verifyFormat("const int result = lhs + rhs;", Style);
+
+ verifyFormat("result = loooooooooooooooooooooongop1 +\n"
+ " loooooooooooooooooooooongop2 +\n"
+ " loooooooooooooooooooooongop3;",
+ Style);
+
+ verifyFormat("const int result =\n"
+ " operand1 + operand2 - (operand3 + operand4);",
+ Style);
+
+ verifyFormat("result = longOperand1 +\n"
+ " longOperand2 -\n"
+ " (longOperand3 + longOperand4) -\n"
+ " longOperand5 +\n"
+ " longOperand6;",
+ Style);
+
+ verifyFormat("result = operand1 +\n"
+ " operand2 -\n"
+ " operand3 +\n"
+ " operand4 -\n"
+ " operand5 +\n"
+ " operand6;",
+ Style);
+
+ // Ensure mixed precedence operations are handled properly
+ verifyFormat("result = op1 + op2 * op3 - op4;", Style);
+
+ verifyFormat("result = operand1 +\n"
+ " operand2 /\n"
+ " operand3 +\n"
+ " operand4 /\n"
+ " operand5 *\n"
+ " operand6;",
+ Style);
+
+ verifyFormat("result = operand1 *\n"
+ " operand2 -\n"
+ " operand3 *\n"
+ " operand4 -\n"
+ " operand5 +\n"
+ " operand6;",
+ Style);
+
+ verifyFormat("result = operand1 *\n"
+ " (operand2 - operand3 * operand4) -\n"
+ " operand5 +\n"
+ " operand6;",
+ Style);
+
+ verifyFormat("result = operand1.member *\n"
+ " (operand2.member() - operand3->mem * operand4) -\n"
+ " operand5.member() +\n"
+ " operand6->member;",
+ Style);
+
+ // Check operator>> special case.
+ verifyFormat("std::cin >>\n"
+ " longOperand_1 >>\n"
+ " longOperand_2 >>\n"
+ " longOperand_3_;",
+ Style);
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_RespectPrecedence;
+ verifyFormat("result = op1 + op2 * op3 - op4;", Style);
+
+ verifyFormat("result = operand1 +\n"
+ " operand2 / operand3 +\n"
+ " operand4 / operand5 * operand6;",
+ Style);
+
+ verifyFormat("result = operand1 * operand2 -\n"
+ " operand3 * operand4 -\n"
+ " operand5 +\n"
+ " operand6;",
+ Style);
+
+ verifyFormat("result = operand1 * (operand2 - operand3 * operand4) -\n"
+ " operand5 +\n"
+ " operand6;",
+ Style);
+
+ verifyFormat("std::uint32_t a = byte_buffer[0] |\n"
+ " byte_buffer[1] << 8 |\n"
+ " byte_buffer[2] << 16 |\n"
+ " byte_buffer[3] << 24;",
+ Style);
+
+ // Check operator>> special case.
+ verifyFormat("std::cin >>\n"
+ " longOperand_1 >>\n"
+ " longOperand_2 >>\n"
+ " longOperand_3_;",
+ Style);
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_OnePerLine;
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+
+ // Logical operations
+ verifyFormat("if (condition1 && condition2) {\n"
+ "}",
+ Style);
+
+ verifyFormat("if (loooooooooooooooooooooongcondition1\n"
+ " && loooooooooooooooooooooongcondition2) {\n"
+ "}",
+ Style);
+
+ // Arithmetic
+ verifyFormat("const int result = lhs + rhs;", Style);
+
+ verifyFormat("result = loooooooooooooooooooooongop1\n"
+ " + loooooooooooooooooooooongop2\n"
+ " + loooooooooooooooooooooongop3;",
+ Style);
+
+ verifyFormat("const int result =\n"
+ " operand1 + operand2 - (operand3 + operand4);",
+ Style);
+
+ verifyFormat("result = longOperand1\n"
+ " + longOperand2\n"
+ " - (longOperand3 + longOperand4)\n"
+ " - longOperand5\n"
+ " + longOperand6;",
+ Style);
+
+ verifyFormat("result = operand1\n"
+ " + operand2\n"
+ " - operand3\n"
+ " + operand4\n"
+ " - operand5\n"
+ " + operand6;",
+ Style);
+
+ // Ensure mixed precedence operations are handled properly
+ verifyFormat("result = op1 + op2 * op3 - op4;", Style);
+
+ verifyFormat("result = operand1\n"
+ " + operand2\n"
+ " / operand3\n"
+ " + operand4\n"
+ " / operand5\n"
+ " * operand6;",
+ Style);
+
+ verifyFormat("result = operand1\n"
+ " * operand2\n"
+ " - operand3\n"
+ " * operand4\n"
+ " - operand5\n"
+ " + operand6;",
+ Style);
+
+ verifyFormat("result = operand1\n"
+ " * (operand2 - operand3 * operand4)\n"
+ " - operand5\n"
+ " + operand6;",
+ Style);
+
+ verifyFormat("std::uint32_t a = byte_buffer[0]\n"
+ " | byte_buffer[1]\n"
+ " << 8\n"
+ " | byte_buffer[2]\n"
+ " << 16\n"
+ " | byte_buffer[3]\n"
+ " << 24;",
+ Style);
+
+ // Check operator>> special case.
+ verifyFormat("std::cin\n"
+ " >> longOperand_1\n"
+ " >> longOperand_2\n"
+ " >> longOperand_3_;",
+ Style);
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_RespectPrecedence;
+ verifyFormat("result = op1 + op2 * op3 - op4;", Style);
+
+ verifyFormat("result = operand1\n"
+ " + operand2 / operand3\n"
+ " + operand4 / operand5 * operand6;",
+ Style);
+
+ verifyFormat("result = operand1 * operand2\n"
+ " - operand3 * operand4\n"
+ " - operand5\n"
+ " + operand6;",
+ Style);
+
+ verifyFormat("result = operand1 * (operand2 - operand3 * operand4)\n"
+ " - operand5\n"
+ " + operand6;",
+ Style);
+
+ verifyFormat("std::uint32_t a = byte_buffer[0]\n"
+ " | byte_buffer[1] << 8\n"
+ " | byte_buffer[2] << 16\n"
+ " | byte_buffer[3] << 24;",
+ Style);
+
+ // Check operator>> special case.
+ verifyFormat("std::cin\n"
+ " >> longOperand_1\n"
+ " >> longOperand_2\n"
+ " >> longOperand_3_;",
+ Style);
+}
+
+TEST_F(FormatTest, BreakBinaryOperationsPerOperator) {
+ auto Style = getLLVMStyleWithColumns(60);
+
+ // Per-operator override: && and || are OnePerLine, rest is Never (default).
+ FormatStyle::BinaryOperationBreakRule LogicalRule;
+ LogicalRule.Operators = {tok::ampamp, tok::pipepipe};
+ LogicalRule.Style = FormatStyle::BBO_OnePerLine;
+ LogicalRule.MinChainLength = 0;
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_Never;
+ Style.BreakBinaryOperations.PerOperator = {LogicalRule};
+
+ // Logical operators break one-per-line when line is too long.
+ verifyFormat("bool valid = isConnectionReady() &&\n"
+ " isSessionNotExpired() &&\n"
+ " hasRequiredPermission();",
+ Style);
+
+ // Arithmetic operators stay with default (Never).
+ verifyFormat("int total = unitBasePrice + shippingCostPerItem +\n"
+ " applicableTaxAmount + handlingFeePerUnit;",
+ Style);
+
+ // Short logical chain that fits stays on one line.
+ verifyFormat("bool x = a && b && c;", Style);
+
+ // Multiple PerOperator groups: && and || plus | operators.
+ FormatStyle::BinaryOperationBreakRule BitwiseOrRule;
+ BitwiseOrRule.Operators = {tok::pipe};
+ BitwiseOrRule.Style = FormatStyle::BBO_OnePerLine;
+ BitwiseOrRule.MinChainLength = 0;
+
+ Style.BreakBinaryOperations.PerOperator = {LogicalRule, BitwiseOrRule};
+
+ // | operators should break one-per-line.
+ verifyFormat("int flags = OPTION_VERBOSE_OUTPUT |\n"
+ " OPTION_RECURSIVE_SCAN |\n"
+ " OPTION_FORCE_OVERWRITE;",
+ Style);
+
+ // && still works in multi-group configuration.
+ verifyFormat("bool valid = isConnectionReady() &&\n"
+ " isSessionNotExpired() &&\n"
+ " hasRequiredPermission();",
+ Style);
+
+ // + stays with default (Never) even with multi-group.
+ verifyFormat("int total = unitBasePrice + shippingCostPerItem +\n"
+ " applicableTaxAmount + handlingFeePerUnit;",
+ Style);
+
+ // | OnePerLine with << sub-expressions: << stays grouped.
+ Style.BreakBinaryOperations.PerOperator = {BitwiseOrRule};
+ verifyFormat("std::uint32_t a = byte_buffer[0] |\n"
+ " byte_buffer[1] << 8 |\n"
+ " byte_buffer[2] << 16 |\n"
+ " byte_buffer[3] << 24;",
+ Style);
+
+ // >> (stream extraction) OnePerLine: clang-format splits >> into two >
+ // tokens, but per-operator rules for >> must still work.
+ FormatStyle::BinaryOperationBreakRule ShiftRightRule;
+ ShiftRightRule.Operators = {tok::greatergreater};
+ ShiftRightRule.Style = FormatStyle::BBO_OnePerLine;
+ ShiftRightRule.MinChainLength = 0;
+
+ Style.BreakBinaryOperations.PerOperator = {ShiftRightRule};
+ verifyFormat("in >>\n"
+ " packet_id >>\n"
+ " packet_version >>\n"
+ " packet_number >>\n"
+ " packet_scale;",
+ Style);
+}
+
+TEST_F(FormatTest, BreakBinaryOperationsMinChainLength) {
+ auto Style = getLLVMStyleWithColumns(60);
+
+ // MinChainLength = 3: chains shorter than 3 don't force breaks.
+ FormatStyle::BinaryOperationBreakRule LogicalRule;
+ LogicalRule.Operators = {tok::ampamp, tok::pipepipe};
+ LogicalRule.Style = FormatStyle::BBO_OnePerLine;
+ LogicalRule.MinChainLength = 3;
+
+ Style.BreakBinaryOperations.Default = FormatStyle::BBO_Never;
+ Style.BreakBinaryOperations.PerOperator = {LogicalRule};
+
+ // Chain of 2 — below MinChainLength, no forced one-per-line.
+ verifyFormat("bool ok =\n"
+ " isConnectionReady(cfg) && isSessionNotExpired(cfg);",
+ Style);
+
+ // Chain of 3 — meets MinChainLength, one-per-line.
+ verifyFormat("bool ok = isConnectionReady(cfg) &&\n"
+ " isSessionNotExpired(cfg) &&\n"
+ " hasRequiredPermission(cfg);",
+ Style);
+
+ // Chain of 4 — above MinChainLength, one-per-line.
+ verifyFormat("bool ok = isConnectionReady(cfg) &&\n"
+ " isSessionNotExpired(cfg) &&\n"
+ " hasRequiredPermission(cfg) &&\n"
+ " isFeatureEnabled(cfg);",
+ Style);
+}
+
+TEST_F(FormatTest, RemoveEmptyLinesInUnwrappedLines) {
+ auto Style = getLLVMStyle();
+ Style.RemoveEmptyLinesInUnwrappedLines = true;
+
+ verifyFormat("int c = a + b;",
+ "int c\n"
+ "\n"
+ " = a + b;",
+ Style);
+
+ verifyFormat("enum : unsigned { AA = 0, BB } myEnum;",
+ "enum : unsigned\n"
+ "\n"
+ "{\n"
+ " AA = 0,\n"
+ " BB\n"
+ "} myEnum;",
+ Style);
+
+ verifyFormat("class B : public E {\n"
+ "private:\n"
+ "};",
+ "class B : public E\n"
+ "\n"
+ "{\n"
+ "private:\n"
+ "};",
+ Style);
+
+ verifyFormat(
+ "struct AAAAAAAAAAAAAAA test[3] = {{56, 23, \"hello\"}, {7, 5, \"!!\"}};",
+ "struct AAAAAAAAAAAAAAA test[3] = {{56,\n"
+ "\n"
+ " 23, \"hello\"},\n"
+ " {7, 5, \"!!\"}};",
+ Style);
+
+ verifyFormat("int myFunction(int aaaaaaaaaaaaa, int ccccccccccccc, int d);",
+ "int myFunction(\n"
+ "\n"
+ " int aaaaaaaaaaaaa,\n"
+ "\n"
+ " int ccccccccccccc, int d);",
+ Style);
+
+ verifyFormat("switch (e) {\n"
+ "case 1:\n"
+ " return e;\n"
+ "case 2:\n"
+ " return 2;\n"
+ "}",
+ "switch (\n"
+ "\n"
+ " e) {\n"
+ "case 1:\n"
+ " return e;\n"
+ "case 2:\n"
+ " return 2;\n"
+ "}",
+ Style);
+
+ verifyFormat("while (true) {\n"
+ "}",
+ "while (\n"
+ "\n"
+ " true) {\n"
+ "}",
+ Style);
+
+ verifyFormat("void loooonFunctionIsVeryLongButNotAsLongAsJavaTypeNames(\n"
+ " std::map<int, std::string> *outputMap);",
+ "void loooonFunctionIsVeryLongButNotAsLongAsJavaTypeNames\n"
+ "\n"
+ " (std::map<int, std::string> *outputMap);",
+ Style);
+}
+
+TEST_F(FormatTest, KeepFormFeed) {
+ auto Style = getLLVMStyle();
+ Style.KeepFormFeed = true;
+
+ constexpr StringRef NoFormFeed("int i;\n"
+ "\n"
+ "void f();");
+ verifyFormat(NoFormFeed,
+ "int i;\n"
+ " \f\n"
+ "void f();",
+ Style);
+ verifyFormat(NoFormFeed,
+ "int i;\n"
+ "\n"
+ "\fvoid f();",
+ Style);
+ verifyFormat(NoFormFeed,
+ "\fint i;\n"
+ "\n"
+ "void f();",
+ Style);
+ verifyFormat(NoFormFeed,
+ "int i;\n"
+ "\n"
+ "void f();\f",
+ Style);
+
+ constexpr StringRef FormFeed("int i;\n"
+ "\f\n"
+ "void f();");
+ verifyNoChange(FormFeed, Style);
+
+ Style.LineEnding = FormatStyle::LE_LF;
+ verifyFormat(FormFeed,
+ "int i;\r\n"
+ "\f\r\n"
+ "void f();",
+ Style);
+
+ constexpr StringRef FormFeedBeforeEmptyLine("int i;\n"
+ "\f\n"
+ "\n"
+ "void f();");
+ Style.MaxEmptyLinesToKeep = 2;
+ verifyFormat(FormFeedBeforeEmptyLine,
+ "int i;\n"
+ "\n"
+ "\f\n"
+ "void f();",
+ Style);
+ verifyFormat(FormFeedBeforeEmptyLine,
+ "int i;\n"
+ "\f\n"
+ "\f\n"
+ "void f();",
+ Style);
+}
+
+TEST_F(FormatTest, ShortNamespacesOption) {
+ auto Style = getLLVMStyleWithColumns(60);
+ Style.AllowShortNamespacesOnASingleLine = true;
+
+ verifyFormat("namespace {\n"
+ "void xxxxx(nnn::TTTTT *mmm, YYYYY &yyyyy);\n"
+ "} // namespace",
+ Style);
+
+ Style.ColumnLimit = 80;
+ Style.CompactNamespaces = true;
+ Style.FixNamespaceComments = false;
+
+ // Basic functionality.
+ verifyFormat("namespace foo { class bar; }", Style);
+ verifyFormat("namespace foo::bar { class baz; }", Style);
+ verifyFormat("namespace { class bar; }", Style);
+ verifyFormat("namespace foo {\n"
+ "class bar;\n"
+ "class baz;\n"
+ "}",
+ Style);
+
+ // Trailing comments prevent merging.
+ verifyFormat("namespace foo { namespace baz {\n"
+ "class qux;\n"
+ "} // comment\n"
+ "}",
+ Style);
+
+ // Make sure code doesn't walk too far on unbalanced code.
+ verifyFormat("namespace foo {", Style);
+ verifyFormat("namespace foo {\n"
+ "class baz;",
+ Style);
+ verifyFormat("namespace foo {\n"
+ "namespace bar { class baz; }",
+ Style);
+
+ // Nested namespaces.
+ verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+
+ // Without CompactNamespaces, we won't merge consecutive namespace
+ // declarations.
+ Style.CompactNamespaces = false;
+ verifyFormat("namespace foo {\n"
+ "namespace bar { class baz; }\n"
+ "}",
+ Style);
+
+ verifyFormat("namespace foo {\n"
+ "namespace bar { class baz; }\n"
+ "namespace qux { class quux; }\n"
+ "}",
+ Style);
+
+ Style.CompactNamespaces = true;
+
+ // Varying inner content.
+ verifyFormat("namespace foo {\n"
+ "int f() { return 5; }\n"
+ "}",
+ Style);
+ verifyFormat("namespace foo { template <T> struct bar; }", Style);
+ verifyFormat("namespace foo { constexpr int num = 42; }", Style);
+
+ // Validate nested namespace wrapping scenarios around the ColumnLimit.
+ Style.ColumnLimit = 64;
+
+ // Validate just under the ColumnLimit.
+ verifyFormat(
+ "namespace foo { namespace bar { namespace baz { class qux; } } }",
+ Style);
+
+ // Validate just over the ColumnLimit.
+ verifyFormat("namespace foo { namespace baar { namespace baaz {\n"
+ "class quux;\n"
+ "}}}",
+ Style);
+
+ verifyFormat(
+ "namespace foo { namespace bar { namespace baz { namespace qux {\n"
+ "class quux;\n"
+ "}}}}",
+ Style);
+
+ // Validate that the ColumnLimit logic accounts for trailing content as well.
+ verifyFormat("namespace foo { namespace bar { class qux; } } // extra",
+ Style);
+
+ verifyFormat("namespace foo { namespace bar { namespace baz {\n"
+ "class qux;\n"
+ "}}} // extra",
+ Style);
+
+ // FIXME: Ideally AllowShortNamespacesOnASingleLine would disable the trailing
+ // namespace comment from 'FixNamespaceComments', as it's not really necessary
+ // in this scenario, but the two options work at very different layers of the
+ // formatter, so I'm not sure how to make them interact.
+ //
+ // As it stands, the trailing comment will be added and likely make the line
+ // too long to fit within the ColumnLimit, reducing the how likely the line
+ // will still fit on a single line. The recommendation for now is to use the
+ // concatenated namespace syntax instead. e.g. 'namespace foo::bar'
+ Style.FixNamespaceComments = true;
+ verifyFormat(
+ "namespace foo { namespace bar { namespace baz {\n"
+ "class qux;\n"
+ "}}} // namespace foo::bar::baz",
+ "namespace foo { namespace bar { namespace baz { class qux; } } }",
+ Style);
+ Style.FixNamespaceComments = false;
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterNamespace = true;
+ verifyFormat("namespace foo { class bar; }", Style);
+ verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+ verifyFormat("namespace foo\n"
+ "{ // comment\n"
+ "class bar;\n"
+ "}",
+ Style);
+ verifyFormat("namespace foo { class bar; }",
+ "namespace foo {\n"
+ "class bar;\n"
+ "}",
+ Style);
+ verifyFormat("namespace foo\n"
+ "{\n"
+ "namespace bar\n"
+ "{ // comment\n"
+ "class baz;\n"
+ "}\n"
+ "}",
+ Style);
+ verifyFormat("namespace foo // comment\n"
+ "{\n"
+ "class baz;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, WrapNamespaceBodyWithEmptyLinesNever) {
+ auto Style = getLLVMStyle();
+ Style.FixNamespaceComments = false;
+ Style.MaxEmptyLinesToKeep = 2;
+ Style.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Never;
+
+ // Empty namespace.
+ verifyFormat("namespace N {}", Style);
+
+ // Single namespace.
+ verifyFormat("namespace N {\n"
+ "int f1(int a) { return 2 * a; }\n"
+ "}",
+ "namespace N {\n"
+ "\n"
+ "\n"
+ "int f1(int a) { return 2 * a; }\n"
+ "\n"
+ "\n"
+ "}",
+ Style);
+
+ // Nested namespace.
+ verifyFormat("namespace N1 {\n"
+ "namespace N2 {\n"
+ "int a = 1;\n"
+ "}\n"
+ "}",
+ "namespace N1 {\n"
+ "\n"
+ "\n"
+ "namespace N2 {\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "}\n"
+ "\n"
+ "\n"
+ "}",
+ Style);
+
+ Style.CompactNamespaces = true;
+
+ verifyFormat("namespace N1 { namespace N2 {\n"
+ "int a = 1;\n"
+ "}}",
+ "namespace N1 { namespace N2 {\n"
+ "\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "\n"
+ "}}",
+ Style);
+}
+
+TEST_F(FormatTest, WrapNamespaceBodyWithEmptyLinesAlways) {
+ auto Style = getLLVMStyle();
+ Style.FixNamespaceComments = false;
+ Style.MaxEmptyLinesToKeep = 2;
+ Style.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Always;
+
+ // Empty namespace.
+ verifyFormat("namespace N {}", Style);
+
+ // Single namespace.
+ verifyFormat("namespace N {\n"
+ "\n"
+ "int f1(int a) { return 2 * a; }\n"
+ "\n"
+ "}",
+ "namespace N {\n"
+ "int f1(int a) { return 2 * a; }\n"
+ "}",
+ Style);
+
+ // Nested namespace.
+ verifyFormat("namespace N1 {\n"
+ "namespace N2 {\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "}\n"
+ "}",
+ "namespace N1 {\n"
+ "namespace N2 {\n"
+ "int a = 1;\n"
+ "}\n"
+ "}",
+ Style);
+
+ verifyFormat("namespace N1 {\n"
+ "\n"
+ "namespace N2 {\n"
+ "\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "\n"
+ "}\n"
+ "\n"
+ "}",
+ "namespace N1 {\n"
+ "\n"
+ "namespace N2 {\n"
+ "\n"
+ "\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "\n"
+ "\n"
+ "}\n"
+ "\n"
+ "}",
+ Style);
+
+ Style.CompactNamespaces = true;
+
+ verifyFormat("namespace N1 { namespace N2 {\n"
+ "\n"
+ "int a = 1;\n"
+ "\n"
+ "}}",
+ "namespace N1 { namespace N2 {\n"
+ "int a = 1;\n"
+ "}}",
+ Style);
+}
+
+TEST_F(FormatTest, BreakBeforeClassName) {
+ verifyFormat("class ABSL_ATTRIBUTE_TRIVIAL_ABI ABSL_NULLABILITY_COMPATIBLE\n"
+ " ArenaSafeUniquePtr {};");
+}
+
+TEST_F(FormatTest, KeywordedFunctionLikeMacros) {
+ constexpr StringRef Code("Q_PROPERTY(int name\n"
+ " READ name\n"
+ " WRITE setName\n"
+ " NOTIFY nameChanged)");
+ constexpr StringRef Code2("class A {\n"
+ " Q_PROPERTY(int name\n"
+ " READ name\n"
+ " WRITE setName\n"
+ " NOTIFY nameChanged)\n"
+ "};");
+
+ auto Style = getLLVMStyle();
+ Style.AllowBreakBeforeQtProperty = true;
+
+ Style.BinPackParameters = FormatStyle::BPPS_AlwaysOnePerLine;
+ verifyFormat(Code, Style);
+ verifyFormat(Code2, Style);
+
+ Style.BinPackParameters = FormatStyle::BPPS_OnePerLine;
+ Style.ColumnLimit = 40;
+ verifyFormat(Code, Style);
+ verifyFormat(Code2, Style);
+ verifyFormat("/* sdf */ Q_PROPERTY(int name\n"
+ " READ name\n"
+ " WRITE setName\n"
+ " NOTIFY nameChanged)",
+ Style);
+}
+
+TEST_F(FormatTest, UnbalancedAngleBrackets) {
+ verifyFormat("template <");
+
+ verifyNoCrash("typename foo<bar>::value, const String &>::type f();",
+ getLLVMStyleWithColumns(50));
+
+ verifyNoCrash(
+ ">\n"
+ " f({\n"
+ " {}inner> () __attribute __attribute__((foo())) int foo(void)\n"
+ " {};\n"
+ " }, );",
+ getLLVMStyleWithColumns(70));
+}
+
+TEST_F(FormatTest, LambdaArrowAsTrailingReturnArrow) {
+ verifyNoCrash("void foo()([] consteval -> int {}())");
+}
+
+} // namespace
+} // namespace test
+} // namespace format
+} // namespace clang
More information about the cfe-commits
mailing list