[clang] [Clang] Allow raw string literals in C as an extension (PR #88265)
@@ -3850,6 +3850,7 @@ LangOptions getFormattingLangOpts(const FormatStyle &Style) { // the sequence "<::" will be unconditionally treated as "[:". // Cf. Lexer::LexTokenInternal. LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11; + LangOpts.RawStringLiterals = LexingStd >= FormatStyle::LS_Cpp11; owenca wrote: Can we set the default to 1 in `LangOpts.def`? That would take care of it. https://github.com/llvm/llvm-project/pull/88265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
owenca wrote: /cherry-pick db0ed5533368 https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't allow comma in front of structural enum (PR #91056)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/91056 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle Java switch expressions (PR #91112)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/91112 >From beab69244ce686a1d53342979d46f269a46c79de Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 5 May 2024 00:21:55 -0700 Subject: [PATCH] [clang-format] Handle Java switch expressions Also adds AllowShortCaseExpressionOnASingleLine option and AlignCaseArrows suboption of AlignConsecutiveShortCaseStatements. Fixes #55903. --- clang/docs/ClangFormatStyleOptions.rst| 36 +++- clang/docs/ReleaseNotes.rst | 3 + clang/include/clang/Format/Format.h | 36 +++- clang/lib/Format/Format.cpp | 4 + clang/lib/Format/FormatToken.h| 3 + clang/lib/Format/TokenAnnotator.cpp | 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 6 + clang/lib/Format/UnwrappedLineParser.cpp | 46 - clang/lib/Format/UnwrappedLineParser.h| 2 +- clang/lib/Format/WhitespaceManager.cpp| 22 ++- clang/lib/Format/WhitespaceManager.h | 2 +- clang/unittests/Format/ConfigParseTest.cpp| 2 + clang/unittests/Format/FormatTestJava.cpp | 171 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 18 ++ 14 files changed, 332 insertions(+), 21 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index ce9035a2770eec..6d092219877f91 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -861,7 +861,8 @@ the configuration (without a prefix: ``Auto``). **AlignConsecutiveShortCaseStatements** (``ShortCaseStatementsAlignmentStyle``) :versionbadge:`clang-format 17` :ref:`¶ ` Style of aligning consecutive short case labels. - Only applies if ``AllowShortCaseLabelsOnASingleLine`` is ``true``. + Only applies if ``AllowShortCaseExpressionOnASingleLine`` or + ``AllowShortCaseLabelsOnASingleLine`` is ``true``. .. code-block:: yaml @@ -935,6 +936,24 @@ the configuration (without a prefix: ``Auto``). default: return ""; } + * ``bool AlignCaseArrows`` Whether to align the case arrows when aligning short case expressions. + +.. code-block:: 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; + }; + * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the tokens after the colon. @@ -1692,6 +1711,21 @@ the configuration (without a prefix: ``Auto``). +.. _AllowShortCaseExpressionOnASingleLine: + +**AllowShortCaseExpressionOnASingleLine** (``Boolean``) :versionbadge:`clang-format 19` :ref:`¶ ` + Whether to merge a short switch labeled rule into a single line. + + .. code-block:: java + +true: false: +switch (a) { vs. switch (a) { +case 1 -> 1;case 1 -> +default -> 0; 1; +}; default -> + 0; +}; + .. _AllowShortCaseLabelsOnASingleLine: **AllowShortCaseLabelsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 3.6` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b146a9b56884ad..a85095e424b64b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -834,6 +834,9 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- Handles Java ``switch`` expressions. +- Adds ``AllowShortCaseExpressionOnASingleLine`` option. +- Adds ``AlignCaseArrows`` suboption to ``AlignConsecutiveShortCaseStatements``. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 8ebdc86b98329c..74893f23210cd0 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -375,6 +375,23 @@ struct FormatStyle { /// } /// \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 @@ -396,12 +
[clang] [clang-format] Handle Java switch expressions (PR #91112)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/91112 >From 31a45ace7d828c63b31d0ba20ed07f2a0340c41d Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 5 May 2024 00:21:55 -0700 Subject: [PATCH] [clang-format] Handle Java switch expressions Also adds AllowShortCaseExpressionOnASingleLine option and AlignCaseArrows suboption of AlignConsecutiveShortCaseStatements. Fixes #55903. --- clang/docs/ClangFormatStyleOptions.rst| 36 +++- clang/docs/ReleaseNotes.rst | 3 + clang/include/clang/Format/Format.h | 36 +++- clang/lib/Format/Format.cpp | 4 + clang/lib/Format/FormatToken.h| 3 + clang/lib/Format/TokenAnnotator.cpp | 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 6 + clang/lib/Format/UnwrappedLineParser.cpp | 46 - clang/lib/Format/UnwrappedLineParser.h| 2 +- clang/lib/Format/WhitespaceManager.cpp| 22 ++- clang/lib/Format/WhitespaceManager.h | 2 +- clang/unittests/Format/ConfigParseTest.cpp| 2 + clang/unittests/Format/FormatTestJava.cpp | 171 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 18 ++ 14 files changed, 332 insertions(+), 21 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index ce9035a2770eec..f0f1f44491251c 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -861,7 +861,8 @@ the configuration (without a prefix: ``Auto``). **AlignConsecutiveShortCaseStatements** (``ShortCaseStatementsAlignmentStyle``) :versionbadge:`clang-format 17` :ref:`¶ ` Style of aligning consecutive short case labels. - Only applies if ``AllowShortCaseLabelsOnASingleLine`` is ``true``. + Only applies if ``AllowShortCaseExpressionOnASingleLine`` or + ``AllowShortCaseLabelsOnASingleLine`` is ``true``. .. code-block:: yaml @@ -935,6 +936,24 @@ the configuration (without a prefix: ``Auto``). default: return ""; } + * ``bool AlignCaseArrows`` Whether to align the case arrows when aligning short case expressions. + +.. code-block:: c++ + + 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; + }; + * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the tokens after the colon. @@ -1692,6 +1711,21 @@ the configuration (without a prefix: ``Auto``). +.. _AllowShortCaseExpressionOnASingleLine: + +**AllowShortCaseExpressionOnASingleLine** (``Boolean``) :versionbadge:`clang-format 19` :ref:`¶ ` + Whether to merge a short switch labeled rule into a single line. + + .. code-block:: c++ + +true: false: +switch (a) { vs. switch (a) { +case 1 -> 1;case 1 -> +default -> 0; 1; +}; default -> + 0; +}; + .. _AllowShortCaseLabelsOnASingleLine: **AllowShortCaseLabelsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 3.6` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b146a9b56884ad..a85095e424b64b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -834,6 +834,9 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- Handles Java ``switch`` expressions. +- Adds ``AllowShortCaseExpressionOnASingleLine`` option. +- Adds ``AlignCaseArrows`` suboption to ``AlignConsecutiveShortCaseStatements``. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 8ebdc86b98329c..7253f3b57b3003 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -375,6 +375,23 @@ struct FormatStyle { /// } /// \endcode bool AcrossComments; +/// Whether to align the case arrows when aligning short case expressions. +/// \code +/// 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 @@ -396,12 +413,14 @@
[clang] [clang-format] Handle Java switch expressions (PR #91112)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/91112 >From be8569c3721337317635a2f0640237a2d5acd73a Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 5 May 2024 00:21:55 -0700 Subject: [PATCH 1/2] [clang-format] Handle Java switch expressions Also adds AllowShortCaseExpressionOnASingleLine option and AlignCaseArrows suboption of AlignConsecutiveShortCaseStatements. Fixes #55903. --- clang/docs/ClangFormatStyleOptions.rst| 36 +++- clang/docs/ReleaseNotes.rst | 3 + clang/include/clang/Format/Format.h | 36 +++- clang/lib/Format/Format.cpp | 4 + clang/lib/Format/FormatToken.h| 3 + clang/lib/Format/TokenAnnotator.cpp | 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 6 + clang/lib/Format/UnwrappedLineParser.cpp | 46 - clang/lib/Format/UnwrappedLineParser.h| 2 +- clang/lib/Format/WhitespaceManager.cpp| 22 ++- clang/lib/Format/WhitespaceManager.h | 2 +- clang/unittests/Format/ConfigParseTest.cpp| 2 + clang/unittests/Format/FormatTestJava.cpp | 171 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 18 ++ 14 files changed, 332 insertions(+), 21 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index ce9035a2770eec..f320caf0d21998 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -861,7 +861,8 @@ the configuration (without a prefix: ``Auto``). **AlignConsecutiveShortCaseStatements** (``ShortCaseStatementsAlignmentStyle``) :versionbadge:`clang-format 17` :ref:`¶ ` Style of aligning consecutive short case labels. - Only applies if ``AllowShortCaseLabelsOnASingleLine`` is ``true``. + Only applies if ``AllowShortCaseExpressionOnASingleLine`` or + ``AllowShortCaseLabelsOnASingleLine`` is ``true``. .. code-block:: yaml @@ -935,6 +936,24 @@ the configuration (without a prefix: ``Auto``). default: return ""; } + * ``bool AlignCaseArrows`` Whether to align the case arrows when aligning short case expressions. + +.. code-block:: c++ + + true: + i = switch (day) {\n" +case THURSDAY, SATURDAY -> 8; +case WEDNESDAY -> 9; +default -> 0; + }; + + false: + i = switch (day) {\n" +case THURSDAY, SATURDAY -> 8; +case WEDNESDAY -> 9; +default -> 0; + }; + * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the tokens after the colon. @@ -1692,6 +1711,21 @@ the configuration (without a prefix: ``Auto``). +.. _AllowShortCaseExpressionOnASingleLine: + +**AllowShortCaseExpressionOnASingleLine** (``Boolean``) :versionbadge:`clang-format 19` :ref:`¶ ` + Whether to merge a short switch labeled rule into a single line. + + .. code-block:: c++ + +true: false: +switch (a) { vs. switch (a) { +case 1 -> 1;case 1 -> +default -> 0; 1; +}; default -> + 0; +}; + .. _AllowShortCaseLabelsOnASingleLine: **AllowShortCaseLabelsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 3.6` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b146a9b56884ad..a85095e424b64b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -834,6 +834,9 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- Handles Java ``switch`` expressions. +- Adds ``AllowShortCaseExpressionOnASingleLine`` option. +- Adds ``AlignCaseArrows`` suboption to ``AlignConsecutiveShortCaseStatements``. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 8ebdc86b98329c..d08db77c2ab063 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -375,6 +375,23 @@ struct FormatStyle { /// } /// \endcode bool AcrossComments; +/// Whether to align the case arrows when aligning short case expressions. +/// \code +/// true: +/// i = switch (day) {\n" +/// case THURSDAY, SATURDAY -> 8; +/// case WEDNESDAY -> 9; +/// default -> 0; +/// }; +/// +/// false: +/// i = switch (day) {\n" +/// 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 @@ -3
[clang] [clang-format] Handle Java switch expressions (PR #91112)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/91112 Also adds AllowShortCaseExpressionOnASingleLine option and AlignCaseArrows suboption of AlignConsecutiveShortCaseStatements. Fixes #55903. >From be8569c3721337317635a2f0640237a2d5acd73a Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 5 May 2024 00:21:55 -0700 Subject: [PATCH] [clang-format] Handle Java switch expressions Also adds AllowShortCaseExpressionOnASingleLine option and AlignCaseArrows suboption of AlignConsecutiveShortCaseStatements. Fixes #55903. --- clang/docs/ClangFormatStyleOptions.rst| 36 +++- clang/docs/ReleaseNotes.rst | 3 + clang/include/clang/Format/Format.h | 36 +++- clang/lib/Format/Format.cpp | 4 + clang/lib/Format/FormatToken.h| 3 + clang/lib/Format/TokenAnnotator.cpp | 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 6 + clang/lib/Format/UnwrappedLineParser.cpp | 46 - clang/lib/Format/UnwrappedLineParser.h| 2 +- clang/lib/Format/WhitespaceManager.cpp| 22 ++- clang/lib/Format/WhitespaceManager.h | 2 +- clang/unittests/Format/ConfigParseTest.cpp| 2 + clang/unittests/Format/FormatTestJava.cpp | 171 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 18 ++ 14 files changed, 332 insertions(+), 21 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index ce9035a2770eec..f320caf0d21998 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -861,7 +861,8 @@ the configuration (without a prefix: ``Auto``). **AlignConsecutiveShortCaseStatements** (``ShortCaseStatementsAlignmentStyle``) :versionbadge:`clang-format 17` :ref:`¶ ` Style of aligning consecutive short case labels. - Only applies if ``AllowShortCaseLabelsOnASingleLine`` is ``true``. + Only applies if ``AllowShortCaseExpressionOnASingleLine`` or + ``AllowShortCaseLabelsOnASingleLine`` is ``true``. .. code-block:: yaml @@ -935,6 +936,24 @@ the configuration (without a prefix: ``Auto``). default: return ""; } + * ``bool AlignCaseArrows`` Whether to align the case arrows when aligning short case expressions. + +.. code-block:: c++ + + true: + i = switch (day) {\n" +case THURSDAY, SATURDAY -> 8; +case WEDNESDAY -> 9; +default -> 0; + }; + + false: + i = switch (day) {\n" +case THURSDAY, SATURDAY -> 8; +case WEDNESDAY -> 9; +default -> 0; + }; + * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the tokens after the colon. @@ -1692,6 +1711,21 @@ the configuration (without a prefix: ``Auto``). +.. _AllowShortCaseExpressionOnASingleLine: + +**AllowShortCaseExpressionOnASingleLine** (``Boolean``) :versionbadge:`clang-format 19` :ref:`¶ ` + Whether to merge a short switch labeled rule into a single line. + + .. code-block:: c++ + +true: false: +switch (a) { vs. switch (a) { +case 1 -> 1;case 1 -> +default -> 0; 1; +}; default -> + 0; +}; + .. _AllowShortCaseLabelsOnASingleLine: **AllowShortCaseLabelsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 3.6` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b146a9b56884ad..a85095e424b64b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -834,6 +834,9 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- Handles Java ``switch`` expressions. +- Adds ``AllowShortCaseExpressionOnASingleLine`` option. +- Adds ``AlignCaseArrows`` suboption to ``AlignConsecutiveShortCaseStatements``. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 8ebdc86b98329c..d08db77c2ab063 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -375,6 +375,23 @@ struct FormatStyle { /// } /// \endcode bool AcrossComments; +/// Whether to align the case arrows when aligning short case expressions. +/// \code +/// true: +/// i = switch (day) {\n" +/// case THURSDAY, SATURDAY -> 8; +/// case WEDNESDAY -> 9; +/// default -> 0; +/// }; +/// +/// false: +/// i = switch (day) {\n" +/// case THURSDAY, SATURDAY -> 8; +/// case WEDNESDAY -> 9; +/// default -> 0; +/// }; +/// \endcode +bool Align
[clang] 9154a32 - [clang-format][doc] Fix typos
Author: Owen Pan Date: 2024-05-05T00:18:55-07:00 New Revision: 9154a324bfce5dee27cb04708bd250b030d6cdd2 URL: https://github.com/llvm/llvm-project/commit/9154a324bfce5dee27cb04708bd250b030d6cdd2 DIFF: https://github.com/llvm/llvm-project/commit/9154a324bfce5dee27cb04708bd250b030d6cdd2.diff LOG: [clang-format][doc] Fix typos Added: Modified: clang/docs/ClangFormatStyleOptions.rst clang/include/clang/Format/Format.h Removed: diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 39f7cded36edbf..ce9035a2770eec 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -935,8 +935,8 @@ the configuration (without a prefix: ``Auto``). default: return ""; } - * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the -, or on the tokens after the colon. + * ``bool AlignCaseColons`` Whether aligned case labels are aligned on the colon, or on the tokens +after the colon. .. code-block:: c++ diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 48f5fb44157570..8ebdc86b98329c 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -375,8 +375,8 @@ struct FormatStyle { /// } /// \endcode bool AcrossComments; -/// Whether aligned case labels are aligned on the colon, or on the -/// , or on the tokens after the colon. +/// Whether aligned case labels are aligned on the colon, or on the tokens +/// after the colon. /// \code /// true: /// switch (level) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
owenca wrote: > I wouldn't worry too much about this, but, pedantically, you can be sure it's > a fold expression if the ellipsis is followed with or preceded by an operator > > https://eel.is/c++draft/expr.prim.fold#nt:fold-operator I had thought of that but decided not to bother. From https://en.cppreference.com/w/cpp/language/fold: ``` op - any of the following 32 binary operators: + - * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->* ``` Because `<` and `>` are on the list, we still wouldn't be able to tell if `...>` is part of a fold expression. Also, I don't like the overhead of up to 32 comparisons. https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a crash with AlignArrayOfStructures option (PR #86420)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/86420 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a crash with AlignArrayOfStructures option (PR #86420)
owenca wrote: /cherry-pick cceedc939a43 https://github.com/llvm/llvm-project/pull/86420 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Allow raw string literals in C as an extension (PR #88265)
@@ -3850,6 +3850,7 @@ LangOptions getFormattingLangOpts(const FormatStyle &Style) { // the sequence "<::" will be unconditionally treated as "[:". // Cf. Lexer::LexTokenInternal. LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11; + LangOpts.RawStringLiterals = LexingStd >= FormatStyle::LS_Cpp11; owenca wrote: As clang-format formats all C code as C++, there's no need to set the new `RawStringLiterals` option here. https://github.com/llvm/llvm-project/pull/88265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/91045 Fixes #90966. >From 2cc5ef7cca02578262795a7f7ea840d0a1496f74 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Fri, 3 May 2024 22:15:33 -0700 Subject: [PATCH] [clang-format] Don't remove parentheses of fold expressions Fixes #90966. --- clang/lib/Format/UnwrappedLineParser.cpp | 7 ++- clang/unittests/Format/FormatTest.cpp| 9 + 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index e8a8dd58d07eea..7d0278bce9a9c6 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2510,6 +2510,7 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { assert(FormatTok->is(tok::l_paren) && "'(' expected."); auto *LeftParen = FormatTok; bool SeenEqual = false; + bool MightBeFoldExpr = false; const bool MightBeStmtExpr = Tokens->peekNextToken()->is(tok::l_brace); nextToken(); do { @@ -2521,7 +2522,7 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { parseChildBlock(); break; case tok::r_paren: - if (!MightBeStmtExpr && !Line->InMacroBody && + if (!MightBeStmtExpr && !MightBeFoldExpr && !Line->InMacroBody && Style.RemoveParentheses > FormatStyle::RPS_Leave) { const auto *Prev = LeftParen->Previous; const auto *Next = Tokens->peekNextToken(); @@ -2564,6 +2565,10 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { parseBracedList(); } break; +case tok::ellipsis: + MightBeFoldExpr = true; + nextToken(); + break; case tok::equal: SeenEqual = true; if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 32ba6b6853c799..e6f8e4a06515ea 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -27204,8 +27204,14 @@ TEST_F(FormatTest, RemoveParentheses) { "if ((({ a; })))\n" " b;", Style); + verifyFormat("static_assert((std::is_constructible_v && ...));", + "static_assert(((std::is_constructible_v && ...)));", + Style); verifyFormat("return (0);", "return (((0)));", Style); verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style); + verifyFormat("return ((... && std::is_convertible_v));", + "return (((... && std::is_convertible_v)));", + Style); Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement; verifyFormat("#define Return0 return (0);", Style); @@ -27213,6 +27219,9 @@ TEST_F(FormatTest, RemoveParentheses) { 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);", + "return (((... && std::is_convertible_v)));", + Style); verifyFormat("inline decltype(auto) f() {\n" " if (a) {\n" "return (a);\n" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] d2af1ea - [clang-format][NFC] Minor improvement to parseLabel()
Author: Owen Pan Date: 2024-05-02T19:42:01-07:00 New Revision: d2af1ea81dd0170133c53ebd67c9a9be125dfd31 URL: https://github.com/llvm/llvm-project/commit/d2af1ea81dd0170133c53ebd67c9a9be125dfd31 DIFF: https://github.com/llvm/llvm-project/commit/d2af1ea81dd0170133c53ebd67c9a9be125dfd31.diff LOG: [clang-format][NFC] Minor improvement to parseLabel() Added: Modified: clang/lib/Format/UnwrappedLineParser.cpp Removed: diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 854428389740d8..e8a8dd58d07eea 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -3201,10 +3201,11 @@ void UnwrappedLineParser::parseDoWhile() { void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) { nextToken(); unsigned OldLineLevel = Line->Level; - if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) ---Line->Level; + if (LeftAlignLabel) Line->Level = 0; + else if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) +--Line->Level; if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [z/OS] treat text files as text files so auto-conversion is done (PR #90128)
@@ -413,8 +413,9 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) { // On Windows, overwriting a file with an open file mapping doesn't work, // so read the whole file into memory when formatting in-place. ErrorOr> CodeOrErr = - !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) -: MemoryBuffer::getFileOrSTDIN(FileName); + !OutputXML && Inplace + ? MemoryBuffer::getFileAsStream(FileName) + : MemoryBuffer::getFileOrSTDIN(FileName, /*IsText=*/true); owenca wrote: I tested it on Windows and didn't have a problem. I used LF only, CRLF only, and mixed line endings for the following: ``` int i; int j; ``` Running clang-format through all values of the `LineEnding` option, with and without in-place, seemed ok. https://github.com/llvm/llvm-project/pull/90128 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in annotating struct braces (PR #90555)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/90555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in annotating struct braces (PR #90555)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/90555 Fixes #60040. >From 77d807d47d47ca9916edc03182e1952c27300a8a Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 29 Apr 2024 21:11:28 -0700 Subject: [PATCH] [clang-format] Fix a bug in annotating struct braces Fixes #60040. --- clang/lib/Format/UnwrappedLineParser.cpp | 5 - clang/unittests/Format/TokenAnnotatorTest.cpp | 13 + 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 3a263955a6a8fe..854428389740d8 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -3944,8 +3944,11 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { switch (FormatTok->Tok.getKind()) { case tok::l_paren: // We can have macros in between 'class' and the class name. - if (!IsNonMacroIdentifier(Previous)) + if (!IsNonMacroIdentifier(Previous) || + // e.g. `struct macro(a) S { int i; };` + Previous->Previous == &InitialToken) { parseParens(); + } break; case tok::coloncolon: break; diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index dff5251d2e9406..01daf8dee505bc 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -438,6 +438,11 @@ TEST_F(TokenAnnotatorTest, UnderstandsStructs) { EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_StructLBrace); EXPECT_TOKEN(Tokens[3], tok::r_brace, TT_StructRBrace); + Tokens = annotate("struct macro(a) S {};"); + ASSERT_EQ(Tokens.size(), 10u) << Tokens; + EXPECT_TOKEN(Tokens[6], tok::l_brace, TT_StructLBrace); + EXPECT_TOKEN(Tokens[7], tok::r_brace, TT_StructRBrace); + Tokens = annotate("struct EXPORT_MACRO [[nodiscard]] C { int i; };"); ASSERT_EQ(Tokens.size(), 15u) << Tokens; EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_StructLBrace); @@ -448,6 +453,14 @@ TEST_F(TokenAnnotatorTest, UnderstandsStructs) { EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_StructLBrace); EXPECT_TOKEN(Tokens[16], tok::r_brace, TT_StructRBrace); + Tokens = annotate("struct macro(a) S {\n" +" void f(T &t);\n" +"};"); + ASSERT_EQ(Tokens.size(), 18u) << Tokens; + EXPECT_TOKEN(Tokens[6], tok::l_brace, TT_StructLBrace); + EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference); + EXPECT_TOKEN(Tokens[15], tok::r_brace, TT_StructRBrace); + Tokens = annotate("template struct S {};"); ASSERT_EQ(Tokens.size(), 18u) << Tokens; EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Set Change.TokenLength to ColumnWidth (PR #90378)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/90378 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Return early in isWordLike() for non-Verilog (PR #90363)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/90363 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Set Change.TokenLength to ColumnWidth (PR #90378)
https://github.com/owenca edited https://github.com/llvm/llvm-project/pull/90378 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Set Change.TokenLength to ColumnWidth (PR #90378)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/90378 Fixes #47333. Fixes #47624. Fixes #75929. Fixes #87885. Fixes #89916. >From d671f32e9bcc6e42e53ddd1799eb0fdef774c142 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 27 Apr 2024 23:34:45 -0700 Subject: [PATCH] [clang-format] Set Change.TokenLength to ColumnWidth Fixes #47333. Fixes #47624. Fixes #75929. Fixes #87885. Fixes #89916. --- clang/lib/Format/WhitespaceManager.cpp | 11 +--- clang/unittests/Format/FormatTest.cpp | 39 ++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp index cc9bcce6c414e0..44fd807ec27ea7 100644 --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -131,6 +131,7 @@ void WhitespaceManager::calculateLineBreakInformation() { for (unsigned I = 1, e = Changes.size(); I != e; ++I) { auto &C = Changes[I]; auto &P = Changes[I - 1]; +auto &PrevTokLength = P.TokenLength; SourceLocation OriginalWhitespaceStart = C.OriginalWhitespaceRange.getBegin(); SourceLocation PreviousOriginalWhitespaceEnd = @@ -169,21 +170,23 @@ void WhitespaceManager::calculateLineBreakInformation() { // line of the token. auto NewlinePos = Text.find_first_of('\n'); if (NewlinePos == StringRef::npos) { - P.TokenLength = OriginalWhitespaceStartOffset - + PrevTokLength = OriginalWhitespaceStartOffset - PreviousOriginalWhitespaceEndOffset + C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size(); + if (!P.IsInsideToken) +PrevTokLength = std::min(PrevTokLength, P.Tok->ColumnWidth); } else { - P.TokenLength = NewlinePos + P.CurrentLinePrefix.size(); + PrevTokLength = NewlinePos + P.CurrentLinePrefix.size(); } // If there are multiple changes in this token, sum up all the changes until // the end of the line. if (P.IsInsideToken && P.NewlinesBefore == 0) - LastOutsideTokenChange->TokenLength += P.TokenLength + P.Spaces; + LastOutsideTokenChange->TokenLength += PrevTokLength + P.Spaces; else LastOutsideTokenChange = &P; -C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + P.TokenLength; +C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + PrevTokLength; P.IsTrailingComment = (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) || diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 8ecc1188a127a5..32ba6b6853c799 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -27363,6 +27363,45 @@ TEST_F(FormatTest, BreakAdjacentStringLiterals) { 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 ii; ///< ii\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); +} + } // namespace } // namespace test } // namespace format ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Return early in isWordLike() for non-Verilog (PR #90363)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/90363 None >From 70e5f7df8711ac22450a441efe91ed7fa6e339f0 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 27 Apr 2024 15:16:43 -0700 Subject: [PATCH] [clang-format][NFC] Return early in isWordLike() for non-Verilog --- clang/lib/Format/FormatToken.h | 8 ++-- clang/lib/Format/TokenAnnotator.cpp | 13 - 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index f651e6228c206d..28b6488e54a422 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -1623,10 +1623,10 @@ struct AdditionalKeywords { IdentifierInfo *kw_then; /// Returns \c true if \p Tok is a keyword or an identifier. - bool isWordLike(const FormatToken &Tok) const { + bool isWordLike(const FormatToken &Tok, bool IsVerilog = true) const { // getIdentifierinfo returns non-null for keywords as well as identifiers. return Tok.Tok.getIdentifierInfo() && - !Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe); + (!IsVerilog || !isVerilogKeywordSymbol(Tok)); } /// Returns \c true if \p Tok is a true JavaScript identifier, returns @@ -1755,6 +1755,10 @@ struct AdditionalKeywords { } } + bool isVerilogKeywordSymbol(const FormatToken &Tok) const { +return Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe); + } + bool isVerilogWordOperator(const FormatToken &Tok) const { return Tok.isOneOf(kw_before, kw_intersect, kw_dist, kw_iff, kw_inside, kw_with); diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 63629fa743184e..d366ae2080bc25 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -4780,9 +4780,14 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, if (Left.Finalized) return Right.hasWhitespaceBefore(); + const bool IsVerilog = Style.isVerilog(); + assert(!IsVerilog || !IsCpp); + // Never ever merge two words. - if (Keywords.isWordLike(Right) && Keywords.isWordLike(Left)) + 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. @@ -5063,12 +5068,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } - } else if (Style.isVerilog()) { + } else if (IsVerilog) { // An escaped identifier ends with whitespace. -if (Style.isVerilog() && Left.is(tok::identifier) && -Left.TokenText[0] == '\\') { +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) && ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] b4af01b - [clang-format][NFC] Don't repeat Changes[i]/Changes[i - 1]
Author: Owen Pan Date: 2024-04-27T15:14:20-07:00 New Revision: b4af01bada0c945906d85c364e12aceaf98b0fae URL: https://github.com/llvm/llvm-project/commit/b4af01bada0c945906d85c364e12aceaf98b0fae DIFF: https://github.com/llvm/llvm-project/commit/b4af01bada0c945906d85c364e12aceaf98b0fae.diff LOG: [clang-format][NFC] Don't repeat Changes[i]/Changes[i - 1] Added: Modified: clang/lib/Format/WhitespaceManager.cpp Removed: diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp index 4f822807dd987d..cc9bcce6c414e0 100644 --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -128,11 +128,13 @@ const tooling::Replacements &WhitespaceManager::generateReplacements() { void WhitespaceManager::calculateLineBreakInformation() { Changes[0].PreviousEndOfTokenColumn = 0; Change *LastOutsideTokenChange = &Changes[0]; - for (unsigned i = 1, e = Changes.size(); i != e; ++i) { + for (unsigned I = 1, e = Changes.size(); I != e; ++I) { +auto &C = Changes[I]; +auto &P = Changes[I - 1]; SourceLocation OriginalWhitespaceStart = -Changes[i].OriginalWhitespaceRange.getBegin(); +C.OriginalWhitespaceRange.getBegin(); SourceLocation PreviousOriginalWhitespaceEnd = -Changes[i - 1].OriginalWhitespaceRange.getEnd(); +P.OriginalWhitespaceRange.getEnd(); unsigned OriginalWhitespaceStartOffset = SourceMgr.getFileOffset(OriginalWhitespaceStart); unsigned PreviousOriginalWhitespaceEndOffset = @@ -167,31 +169,26 @@ void WhitespaceManager::calculateLineBreakInformation() { // line of the token. auto NewlinePos = Text.find_first_of('\n'); if (NewlinePos == StringRef::npos) { - Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset - - PreviousOriginalWhitespaceEndOffset + - Changes[i].PreviousLinePostfix.size() + - Changes[i - 1].CurrentLinePrefix.size(); + P.TokenLength = OriginalWhitespaceStartOffset - + PreviousOriginalWhitespaceEndOffset + + C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size(); } else { - Changes[i - 1].TokenLength = - NewlinePos + Changes[i - 1].CurrentLinePrefix.size(); + P.TokenLength = NewlinePos + P.CurrentLinePrefix.size(); } // If there are multiple changes in this token, sum up all the changes until // the end of the line. -if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) { - LastOutsideTokenChange->TokenLength += - Changes[i - 1].TokenLength + Changes[i - 1].Spaces; -} else { - LastOutsideTokenChange = &Changes[i - 1]; -} +if (P.IsInsideToken && P.NewlinesBefore == 0) + LastOutsideTokenChange->TokenLength += P.TokenLength + P.Spaces; +else + LastOutsideTokenChange = &P; -Changes[i].PreviousEndOfTokenColumn = -Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength; +C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + P.TokenLength; -Changes[i - 1].IsTrailingComment = -(Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) || - (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) && -Changes[i - 1].Tok->is(tok::comment) && +P.IsTrailingComment = +(C.NewlinesBefore > 0 || C.Tok->is(tok::eof) || + (C.IsInsideToken && C.Tok->is(tok::comment))) && +P.Tok->is(tok::comment) && // FIXME: This is a dirty hack. The problem is that // BreakableLineCommentSection does comment reflow changes and here is // the aligning of trailing comments. Consider the case where we reflow ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add a space after a word token only if required (PR #90161)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/90161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add a space after a word token only if required (PR #90161)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/90161 Fixes #78166. >From 3f59076142bd6a87f4875dc79e95e4570f4af7c2 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Thu, 25 Apr 2024 20:08:03 -0700 Subject: [PATCH] [clang-format] Add a space after a word token only if required Fixes #78166. --- clang/lib/Format/TokenAnnotator.cpp | 26 +++--- clang/unittests/Format/FormatTest.cpp | 25 + 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index cdfb4256e41d93..63629fa743184e 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -4834,10 +4834,8 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } -if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && -Right.TokenText[0] == '.') { - return false; -} +if (Left.Tok.getIdentifierInfo() && Right.is(tok::numeric_constant)) + return Right.TokenText[0] != '.'; } else if (Style.isProto()) { if (Right.is(tok::period) && Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, @@ -5266,21 +5264,11 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, return true; } if (Left.is(TT_UnaryOperator)) { -if (Right.isNot(tok::l_paren)) { - // The alternative operators for ~ and ! are "compl" and "not". - // If they are used instead, we do not want to combine them with - // the token to the right, unless that is a left paren. - if (Left.is(tok::exclaim) && Left.TokenText == "not") -return true; - if (Left.is(tok::tilde) && Left.TokenText == "compl") -return true; - // 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; -} -return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) || - Right.is(TT_BinaryOperator); +// 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; +return Style.SpaceAfterLogicalNot && Left.is(tok::exclaim); } // If the next token is a binary operator or a selector name, we have diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index bc61b9c089e922..8ecc1188a127a5 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -24507,16 +24507,25 @@ TEST_F(FormatTest, AlternativeOperators) { verifyFormat("int a compl(5);"); verifyFormat("int a not(5);"); - /* FIXME handle alternate tokens - * https://en.cppreference.com/w/cpp/language/operator_alternative - // alternative tokens - verifyFormat("compl foo();"); // ~foo(); - verifyFormat("foo() <%%>;"); // foo(); - verifyFormat("void foo() <%%>;"); // void foo(){} - verifyFormat("int a <:1:>;"); // int a[1];[ + 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("a = v(not;);\n" + "b = 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(not!) \\\n" + " V(other)", + getLLVMStyleWithColumns(40)); } TEST_F(FormatTest, STLWhileNotDefineChed) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] adds a space after not inside macros (PR #78176)
https://github.com/owenca unassigned https://github.com/llvm/llvm-project/pull/78176 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca edited https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/77456 >From 6c184f9714c94af94c7692e1264061b8dc14e912 Mon Sep 17 00:00:00 2001 From: NorthBlue333 Date: Tue, 9 Jan 2024 14:01:14 +0100 Subject: [PATCH 1/3] [clang-format] Do not update cursor pos if no includes replacement Signed-off-by: NorthBlue333 --- clang/lib/Format/Format.cpp | 3 + clang/unittests/Format/SortIncludesTest.cpp | 119 +++- 2 files changed, 119 insertions(+), 3 deletions(-) diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 46ed5baaeacead..e12ad2ced38285 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3114,6 +3114,7 @@ static void sortCppIncludes(const FormatStyle &Style, return; } + const auto OldCursor = Cursor ? *Cursor : 0; std::string result; for (unsigned Index : Indices) { if (!result.empty()) { @@ -3137,6 +3138,8 @@ static void sortCppIncludes(const FormatStyle &Style, // 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; } diff --git a/clang/unittests/Format/SortIncludesTest.cpp b/clang/unittests/Format/SortIncludesTest.cpp index 772eb53806b4b1..791ab7bb185ed9 100644 --- a/clang/unittests/Format/SortIncludesTest.cpp +++ b/clang/unittests/Format/SortIncludesTest.cpp @@ -6,19 +6,19 @@ // //===--===// -#include "FormatTestUtils.h" +#include "FormatTestBase.h" #include "clang/Format/Format.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Debug.h" #include "gtest/gtest.h" -#define DEBUG_TYPE "format-test" +#define DEBUG_TYPE "sort-includes-test" namespace clang { namespace format { namespace { -class SortIncludesTest : public ::testing::Test { +class SortIncludesTest : public test::FormatTestBase { protected: std::vector GetCodeRange(StringRef Code) { return std::vector(1, tooling::Range(0, Code.size())); @@ -821,6 +821,119 @@ TEST_F(SortIncludesTest, CalculatesCorrectCursorPositionWithRegrouping) { EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line } +TEST_F(SortIncludesTest, + CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = { + {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + verifyNoChange(Code); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ(14u, newCursor(Code, 14)); + EXPECT_EQ(16u, newCursor(Code, 16)); + EXPECT_EQ(30u, newCursor(Code, 30)); + EXPECT_EQ(32u, newCursor(Code, 32)); + EXPECT_EQ(46u, newCursor(Code, 46)); + EXPECT_EQ(48u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = {{".*", 0, 0, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + std::string Expected = "#include \"a\"\r\n" // Start of line: 0 + "#include \"b\"\r\n" // Start of line: 14 + "#include \"c\"\r\n" // Start of line: 28 + "\r\n" // Start of line: 42 + "int i;";// Start of line: 44 + EXPECT_EQ(Expected, sort(Code)); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ( + 14u, + newCursor(Code, 14)); // cursor on empty line in include block is ignored + EXPECT_EQ(14u, newCursor(Code, 16)); + EXPECT_EQ( + 30u, + newCursor(Code, 30)); // cursor on empty line in include block is ignored + EXPECT_EQ(28u, newCursor(Code, 32)); + EXPECT_EQ(42u, newCursor(Code, 46)); + EXPECT_EQ(44u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + Calculates
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/77456 >From 6c184f9714c94af94c7692e1264061b8dc14e912 Mon Sep 17 00:00:00 2001 From: NorthBlue333 Date: Tue, 9 Jan 2024 14:01:14 +0100 Subject: [PATCH 1/2] [clang-format] Do not update cursor pos if no includes replacement Signed-off-by: NorthBlue333 --- clang/lib/Format/Format.cpp | 3 + clang/unittests/Format/SortIncludesTest.cpp | 119 +++- 2 files changed, 119 insertions(+), 3 deletions(-) diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 46ed5baaeacead..e12ad2ced38285 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3114,6 +3114,7 @@ static void sortCppIncludes(const FormatStyle &Style, return; } + const auto OldCursor = Cursor ? *Cursor : 0; std::string result; for (unsigned Index : Indices) { if (!result.empty()) { @@ -3137,6 +3138,8 @@ static void sortCppIncludes(const FormatStyle &Style, // 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; } diff --git a/clang/unittests/Format/SortIncludesTest.cpp b/clang/unittests/Format/SortIncludesTest.cpp index 772eb53806b4b1..791ab7bb185ed9 100644 --- a/clang/unittests/Format/SortIncludesTest.cpp +++ b/clang/unittests/Format/SortIncludesTest.cpp @@ -6,19 +6,19 @@ // //===--===// -#include "FormatTestUtils.h" +#include "FormatTestBase.h" #include "clang/Format/Format.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Debug.h" #include "gtest/gtest.h" -#define DEBUG_TYPE "format-test" +#define DEBUG_TYPE "sort-includes-test" namespace clang { namespace format { namespace { -class SortIncludesTest : public ::testing::Test { +class SortIncludesTest : public test::FormatTestBase { protected: std::vector GetCodeRange(StringRef Code) { return std::vector(1, tooling::Range(0, Code.size())); @@ -821,6 +821,119 @@ TEST_F(SortIncludesTest, CalculatesCorrectCursorPositionWithRegrouping) { EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line } +TEST_F(SortIncludesTest, + CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = { + {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + verifyNoChange(Code); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ(14u, newCursor(Code, 14)); + EXPECT_EQ(16u, newCursor(Code, 16)); + EXPECT_EQ(30u, newCursor(Code, 30)); + EXPECT_EQ(32u, newCursor(Code, 32)); + EXPECT_EQ(46u, newCursor(Code, 46)); + EXPECT_EQ(48u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = {{".*", 0, 0, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + std::string Expected = "#include \"a\"\r\n" // Start of line: 0 + "#include \"b\"\r\n" // Start of line: 14 + "#include \"c\"\r\n" // Start of line: 28 + "\r\n" // Start of line: 42 + "int i;";// Start of line: 44 + EXPECT_EQ(Expected, sort(Code)); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ( + 14u, + newCursor(Code, 14)); // cursor on empty line in include block is ignored + EXPECT_EQ(14u, newCursor(Code, 16)); + EXPECT_EQ( + 30u, + newCursor(Code, 30)); // cursor on empty line in include block is ignored + EXPECT_EQ(28u, newCursor(Code, 32)); + EXPECT_EQ(42u, newCursor(Code, 46)); + EXPECT_EQ(44u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + Calculates
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
owenca wrote: > I have squashed the commits in only one. Note that I have left the failing > tests in the commit, I am not sure if I should remove them or not. Unfortunately, this wiped out my updates that fixed a formatting error and added `#if 0` for the failing tests. https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Annotate enum braces as BK_Block (PR #89871)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89871 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Remove YAML hack to emit a BasedOnStyle comment (PR #89228)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/89228 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Annotate enum braces as BK_Block (PR #89871)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/89871 Fixes #89759. >From dfd275f3d2f89e2cabffcc0d573f2b4571c0ead4 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Tue, 23 Apr 2024 21:59:43 -0700 Subject: [PATCH] [clang-format] Annotate enum braces as BK_Block Fixes #89759. --- clang/lib/Format/UnwrappedLineParser.cpp | 24 +-- clang/unittests/Format/TokenAnnotatorTest.cpp | 17 + 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 6e4e6901e473f7..3a263955a6a8fe 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -534,11 +534,11 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { case tok::r_brace: if (LBraceStack.empty()) break; - if (LBraceStack.back().Tok->is(BK_Unknown)) { + if (auto *LBrace = LBraceStack.back().Tok; LBrace->is(BK_Unknown)) { bool ProbablyBracedList = false; if (Style.Language == FormatStyle::LK_Proto) { ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); -} else { +} else if (LBrace->isNot(TT_EnumLBrace)) { // Using OriginalColumn to distinguish between ObjC methods and // binary operators is a bit hacky. bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && @@ -552,7 +552,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { // If we already marked the opening brace as braced list, the closing // must also be part of it. - ProbablyBracedList = LBraceStack.back().Tok->is(TT_BracedListLBrace); + ProbablyBracedList = LBrace->is(TT_BracedListLBrace); ProbablyBracedList = ProbablyBracedList || (Style.isJavaScript() && @@ -608,13 +608,9 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { ProbablyBracedList = true; } } -if (ProbablyBracedList) { - Tok->setBlockKind(BK_BracedInit); - LBraceStack.back().Tok->setBlockKind(BK_BracedInit); -} else { - Tok->setBlockKind(BK_Block); - LBraceStack.back().Tok->setBlockKind(BK_Block); -} +const auto BlockKind = ProbablyBracedList ? BK_BracedInit : BK_Block; +Tok->setBlockKind(BlockKind); +LBrace->setBlockKind(BlockKind); } LBraceStack.pop_back(); break; @@ -2418,6 +2414,7 @@ bool UnwrappedLineParser::tryToParseChildBlock() { } bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) { + assert(!IsAngleBracket || !IsEnum); bool HasError = false; // FIXME: Once we have an expression parser in the UnwrappedLineParser, @@ -2440,8 +2437,11 @@ bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) { } } if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) { - if (IsEnum && !Style.AllowShortEnumsOnASingleLine) -addUnwrappedLine(); + if (IsEnum) { +FormatTok->setBlockKind(BK_Block); +if (!Style.AllowShortEnumsOnASingleLine) + addUnwrappedLine(); + } nextToken(); return !HasError; } diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 6b8ab441cb46f8..dff5251d2e9406 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -2915,6 +2915,23 @@ TEST_F(TokenAnnotatorTest, BraceKind) { ASSERT_EQ(Tokens.size(), 10u) << Tokens; EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit); EXPECT_BRACE_KIND(Tokens[7], BK_BracedInit); + + Tokens = annotate("#ifdef DEBUG_ENABLED\n" +"#else\n" +"#endif\n" +"class RenderingServer : Object {\n" +"#ifndef DISABLE_DEPRECATED\n" +" enum Features {\n" +"FEATURE_SHADERS,\n" +"FEATURE_MULTITHREADED,\n" +" };\n" +"#endif\n" +"};"); + ASSERT_EQ(Tokens.size(), 29u) << Tokens; + EXPECT_BRACE_KIND(Tokens[11], BK_Block); + EXPECT_BRACE_KIND(Tokens[17], BK_Block); + EXPECT_BRACE_KIND(Tokens[22], BK_Block); + EXPECT_BRACE_KIND(Tokens[26], BK_Block); } TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Correctly annotate list init braces of class types (PR #89706)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89706 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Correctly annotate list init braces of class types (PR #89706)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/89706 Fixes #71939. >From 0fab05c4ab7ac95d7c08dd23a0441dc28c2ef813 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 22 Apr 2024 21:56:31 -0700 Subject: [PATCH] [clang-format] Correctly annotate list init braces of class types Fixes #71939. --- clang/lib/Format/UnwrappedLineParser.cpp | 41 +++-- clang/unittests/Format/TokenAnnotatorTest.cpp | 60 +++ 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 603268f771ac52..6e4e6901e473f7 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -819,8 +819,11 @@ FormatToken *UnwrappedLineParser::parseBlock(bool MustBeDeclaration, return IfLBrace; } - if (FormatTok->is(tok::r_brace) && Tok->is(TT_NamespaceLBrace)) -FormatTok->setFinalizedType(TT_NamespaceRBrace); + if (FormatTok->is(tok::r_brace)) { +FormatTok->setBlockKind(BK_Block); +if (Tok->is(TT_NamespaceLBrace)) + FormatTok->setFinalizedType(TT_NamespaceRBrace); + } const bool IsFunctionRBrace = FormatTok->is(tok::r_brace) && Tok->is(TT_FunctionLBrace); @@ -3910,6 +3913,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { const FormatToken &InitialToken = *FormatTok; nextToken(); + const FormatToken *ClassName = nullptr; + bool IsDerived = false; auto IsNonMacroIdentifier = [](const FormatToken *Tok) { return Tok->is(tok::identifier) && Tok->TokenText != Tok->TokenText.upper(); }; @@ -3934,15 +3939,35 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { } if (FormatTok->is(tok::l_square) && handleCppAttributes()) continue; +const auto *Previous = FormatTok; nextToken(); -// We can have macros in between 'class' and the class name. -if (!IsNonMacroIdentifier(FormatTok->Previous) && -FormatTok->is(tok::l_paren)) { - parseParens(); +switch (FormatTok->Tok.getKind()) { +case tok::l_paren: + // We can have macros in between 'class' and the class name. + if (!IsNonMacroIdentifier(Previous)) +parseParens(); + break; +case tok::coloncolon: + break; +default: + if (!ClassName && Previous->is(tok::identifier)) +ClassName = Previous; } } + auto IsListInitialization = [&] { +if (!ClassName || IsDerived) + return false; +assert(FormatTok->is(tok::l_brace)); +const auto *Prev = FormatTok->getPreviousNonComment(); +assert(Prev); +return Prev != ClassName && Prev->is(tok::identifier) && + Prev->isNot(Keywords.kw_final) && tryToParseBracedList(); + }; + if (FormatTok->isOneOf(tok::colon, tok::less)) { +if (FormatTok->is(tok::colon)) + IsDerived = true; int AngleNestingLevel = 0; do { if (FormatTok->is(tok::less)) @@ -3955,6 +3980,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { break; } if (FormatTok->is(tok::l_brace)) { +if (AngleNestingLevel == 0 && IsListInitialization()) + return; calculateBraceTypes(/*ExpectClassBody=*/true); if (!tryToParseBracedList()) break; @@ -3999,6 +4026,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { } }; if (FormatTok->is(tok::l_brace)) { +if (IsListInitialization()) + return; auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken); FormatTok->setFinalizedType(OpenBraceType); if (ParseAsExpr) { diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 34999b7376397b..6b8ab441cb46f8 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -2855,6 +2855,66 @@ TEST_F(TokenAnnotatorTest, BraceKind) { ASSERT_EQ(Tokens.size(), 18u) << Tokens; EXPECT_BRACE_KIND(Tokens[8], BK_BracedInit); EXPECT_BRACE_KIND(Tokens[16], BK_BracedInit); + + Tokens = annotate("struct {};"); + ASSERT_EQ(Tokens.size(), 5u) << Tokens; + EXPECT_BRACE_KIND(Tokens[1], BK_Block); + EXPECT_BRACE_KIND(Tokens[2], BK_Block); + + Tokens = annotate("struct : Base {};"); + ASSERT_EQ(Tokens.size(), 7u) << Tokens; + EXPECT_BRACE_KIND(Tokens[3], BK_Block); + EXPECT_BRACE_KIND(Tokens[4], BK_Block); + + Tokens = annotate("struct Foo {};"); + ASSERT_EQ(Tokens.size(), 6u) << Tokens; + EXPECT_BRACE_KIND(Tokens[2], BK_Block); + EXPECT_BRACE_KIND(Tokens[3], BK_Block); + + Tokens = annotate("struct ::Foo {};"); + ASSERT_EQ(Tokens.size(), 7u) << Tokens; + EXPECT_BRACE_KIND(Tokens[3], BK_Block); + EXPECT_BRACE_KIND(Tokens[4], BK_Block); + + Tokens = annotate("struct NS::Foo {};"); + ASSERT_EQ(Tokens.size(), 8u) << Tokens; + EXPECT_BRACE_KIND(Tokens[4], BK_Block); + EXPECT_BRACE_KIND(Tokens[5], BK_Block); + + Tokens = annotate("struct Foo {};"); +
[clang] [clang-format] Fix a bug in annotating CastRParen before unary && (PR #89346)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89346 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)
owenca wrote: /cherry-pick 29ecd6d50f14 https://github.com/llvm/llvm-project/pull/89016 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)
owenca wrote: Yep. https://github.com/llvm/llvm-project/pull/89016 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating TrailingReturnArrow (PR #86624)
owenca wrote: /cherry-pick a7f4576ff4e2 https://github.com/llvm/llvm-project/pull/86624 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in ContinuationIndenter (PR #88414)
owenca wrote: /cherry-pick d61edecbfd09 https://github.com/llvm/llvm-project/pull/88414 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating BK_BracedInit (PR #87450)
owenca wrote: /cherry-pick 7c9c38eaa9b7 https://github.com/llvm/llvm-project/pull/87450 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
owenca wrote: /cherry-pick 58323de2e5ed https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
owenca wrote: Ah, I still need to do that. https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
owenca wrote: @tstellar somehow this is not in 18.1.4, but the LLVM Release Status in the Projects box says "Status: Done". Did I miss something here? https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
owenca wrote: > I've done all your changes in a second commit just to be able to keep track > of my previous changes; but I am actually not sure how your suggested > modifications are any different from mine? Well, I admit it looks a bit > better, but it works the same? Or am I missing something? You are just > storing the old value of Cursor and resetting it when no changes, while I was > doing it the other way around: storing the new value and updating it only if > no changes. It's been a while, but IIRC your original fix was not equivalent to my suggestion, which IMO is simpler and cleaner. > It does not fix the tests I mentioned. My bad. I copy-pasted the two tests you said would fail and ran FormatTests with my suggested fix, and they passed. Of course, I missed the comments in your snippet, e.g.: ``` EXPECT_EQ(15u, newCursor(Code, 14)); // FIXME: should expect 16, caused by \r ``` https://github.com/llvm/llvm-project/pull/77456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/77456 >From d4fd95374a82361e3dbfcd7a5d87c37da4542d2b Mon Sep 17 00:00:00 2001 From: NorthBlue333 Date: Tue, 9 Jan 2024 14:01:14 +0100 Subject: [PATCH 1/4] [clang-format] Do not update cursor pos if no includes replacement --- clang/lib/Format/Format.cpp | 13 +++-- clang/unittests/Format/SortIncludesTest.cpp | 61 - 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 46ed5baaeacead..17a3e0c9cfd733 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3115,6 +3115,7 @@ static void sortCppIncludes(const FormatStyle &Style, } std::string result; + unsigned NewCursor = UINT_MAX; for (unsigned Index : Indices) { if (!result.empty()) { result += "\n"; @@ -3126,13 +3127,10 @@ static void sortCppIncludes(const FormatStyle &Style, } result += Includes[Index].Text; if (Cursor && CursorIndex == Index) - *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset; + NewCursor = 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( @@ -3140,6 +3138,13 @@ static void sortCppIncludes(const FormatStyle &Style, return; } + if (Cursor) { +if (NewCursor != UINT_MAX) + *Cursor = NewCursor; +else if (*Cursor >= IncludesEndOffset) + *Cursor += result.size() - IncludesBlockSize; + } + auto Err = Replaces.add(tooling::Replacement( FileName, Includes.front().Offset, IncludesBlockSize, result)); // FIXME: better error handling. For now, just skip the replacement for the diff --git a/clang/unittests/Format/SortIncludesTest.cpp b/clang/unittests/Format/SortIncludesTest.cpp index 772eb53806b4b1..939ad181a9d707 100644 --- a/clang/unittests/Format/SortIncludesTest.cpp +++ b/clang/unittests/Format/SortIncludesTest.cpp @@ -6,19 +6,19 @@ // //===--===// -#include "FormatTestUtils.h" +#include "FormatTestBase.h" #include "clang/Format/Format.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Debug.h" #include "gtest/gtest.h" -#define DEBUG_TYPE "format-test" +#define DEBUG_TYPE "sort-includes-test" namespace clang { namespace format { namespace { -class SortIncludesTest : public ::testing::Test { +class SortIncludesTest : public test::FormatTestBase { protected: std::vector GetCodeRange(StringRef Code) { return std::vector(1, tooling::Range(0, Code.size())); @@ -821,6 +821,61 @@ TEST_F(SortIncludesTest, CalculatesCorrectCursorPositionWithRegrouping) { EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line } +TEST_F(SortIncludesTest, + CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = { + {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + verifyNoChange(Code); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ(14u, newCursor(Code, 14)); + EXPECT_EQ(16u, newCursor(Code, 16)); + EXPECT_EQ(30u, newCursor(Code, 30)); + EXPECT_EQ(32u, newCursor(Code, 32)); + EXPECT_EQ(46u, newCursor(Code, 46)); + EXPECT_EQ(48u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = {{".*", 0, 0, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + std::string Expected = "#include \"a\"\r\n" // Start of line: 0
[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/77456 >From d4fd95374a82361e3dbfcd7a5d87c37da4542d2b Mon Sep 17 00:00:00 2001 From: NorthBlue333 Date: Tue, 9 Jan 2024 14:01:14 +0100 Subject: [PATCH 1/3] [clang-format] Do not update cursor pos if no includes replacement --- clang/lib/Format/Format.cpp | 13 +++-- clang/unittests/Format/SortIncludesTest.cpp | 61 - 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 46ed5baaeacead..17a3e0c9cfd733 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3115,6 +3115,7 @@ static void sortCppIncludes(const FormatStyle &Style, } std::string result; + unsigned NewCursor = UINT_MAX; for (unsigned Index : Indices) { if (!result.empty()) { result += "\n"; @@ -3126,13 +3127,10 @@ static void sortCppIncludes(const FormatStyle &Style, } result += Includes[Index].Text; if (Cursor && CursorIndex == Index) - *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset; + NewCursor = 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( @@ -3140,6 +3138,13 @@ static void sortCppIncludes(const FormatStyle &Style, return; } + if (Cursor) { +if (NewCursor != UINT_MAX) + *Cursor = NewCursor; +else if (*Cursor >= IncludesEndOffset) + *Cursor += result.size() - IncludesBlockSize; + } + auto Err = Replaces.add(tooling::Replacement( FileName, Includes.front().Offset, IncludesBlockSize, result)); // FIXME: better error handling. For now, just skip the replacement for the diff --git a/clang/unittests/Format/SortIncludesTest.cpp b/clang/unittests/Format/SortIncludesTest.cpp index 772eb53806b4b1..939ad181a9d707 100644 --- a/clang/unittests/Format/SortIncludesTest.cpp +++ b/clang/unittests/Format/SortIncludesTest.cpp @@ -6,19 +6,19 @@ // //===--===// -#include "FormatTestUtils.h" +#include "FormatTestBase.h" #include "clang/Format/Format.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Debug.h" #include "gtest/gtest.h" -#define DEBUG_TYPE "format-test" +#define DEBUG_TYPE "sort-includes-test" namespace clang { namespace format { namespace { -class SortIncludesTest : public ::testing::Test { +class SortIncludesTest : public test::FormatTestBase { protected: std::vector GetCodeRange(StringRef Code) { return std::vector(1, tooling::Range(0, Code.size())); @@ -821,6 +821,61 @@ TEST_F(SortIncludesTest, CalculatesCorrectCursorPositionWithRegrouping) { EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line } +TEST_F(SortIncludesTest, + CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = { + {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + verifyNoChange(Code); + EXPECT_EQ(0u, newCursor(Code, 0)); + EXPECT_EQ(14u, newCursor(Code, 14)); + EXPECT_EQ(16u, newCursor(Code, 16)); + EXPECT_EQ(30u, newCursor(Code, 30)); + EXPECT_EQ(32u, newCursor(Code, 32)); + EXPECT_EQ(46u, newCursor(Code, 46)); + EXPECT_EQ(48u, newCursor(Code, 48)); +} + +TEST_F( +SortIncludesTest, + CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF) { + Style.IncludeBlocks = Style.IBS_Regroup; + FmtStyle.LineEnding = FormatStyle::LE_CRLF; + Style.IncludeCategories = {{".*", 0, 0, false}}; + std::string Code = "#include \"a\"\r\n" // Start of line: 0 + "\r\n" // Start of line: 14 + "#include \"b\"\r\n" // Start of line: 16 + "\r\n" // Start of line: 30 + "#include \"c\"\r\n" // Start of line: 32 + "\r\n" // Start of line: 46 + "int i;";// Start of line: 48 + std::string Expected = "#include \"a\"\r\n" // Start of line: 0
[clang] [clang-format] Fix a bug in annotating CastRParen before unary && (PR #89346)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/89346 Also fix a bug in annotating TrailingAnnotation. Closes #61233. >From 53b2846e35e0e8541ca0c3c6f63d31821dc9441c Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Thu, 18 Apr 2024 21:21:47 -0700 Subject: [PATCH] [clang-format] Fix a bug in annotating CastRParen before unary && Also fix a bug in annotating TrailingAnnotation. Closes #61233. --- clang/lib/Format/TokenAnnotator.cpp | 5 - clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index a679683077ac94..cdfb4256e41d93 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1543,6 +1543,7 @@ class AnnotatingParser { return false; if (Line.MustBeDeclaration && Contexts.size() == 1 && !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && + !Line.startsWith(tok::l_paren) && !Tok->isOneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen)) { if (const auto *Previous = Tok->Previous; !Previous || @@ -2726,8 +2727,10 @@ class AnnotatingParser { } } -if (Tok.Next->isOneOf(tok::question, tok::ampamp)) +if (Tok.Next->is(tok::question) || +(Tok.Next->is(tok::ampamp) && !Tok.Previous->isTypeName(IsCpp))) { return false; +} // `foreach((A a, B b) in someList)` should not be seen as a cast. if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp()) diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 4f445c64ab303a..34999b7376397b 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -599,6 +599,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) { ASSERT_EQ(Tokens.size(), 6u) << Tokens; EXPECT_TOKEN(Tokens[2], tok::r_paren, TT_CastRParen); + Tokens = annotate("(uint32_t)&&label;"); + ASSERT_EQ(Tokens.size(), 7u) << Tokens; + EXPECT_TOKEN(Tokens[2], tok::r_paren, TT_CastRParen); + EXPECT_TOKEN(Tokens[3], tok::ampamp, TT_UnaryOperator); + EXPECT_TOKEN(Tokens[4], tok::identifier, TT_Unknown); + Tokens = annotate("auto x = (Foo)p;"); ASSERT_EQ(Tokens.size(), 9u) << Tokens; EXPECT_TOKEN(Tokens[5], tok::r_paren, TT_CastRParen); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Annotate ampamp after new/delete as BinaryOperator (PR #89033)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89033 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89016 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Annotate ampamp after new/delete as BinaryOperator (PR #89033)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/89033 Fixes #78789. >From 0e2d91d20a1c318868f2e791d859a047b83f0277 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Wed, 17 Apr 2024 00:39:36 -0700 Subject: [PATCH] [clang-format] Annotate ampamp after new/delete as BinaryOperator Fixes #78789. --- clang/lib/Format/TokenAnnotator.cpp | 2 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 10 ++ 2 files changed, 12 insertions(+) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 628f70417866c3..272d7bbb352daf 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -2912,6 +2912,8 @@ class AnnotatingParser { return TT_UnaryOperator; if (PrevToken->is(TT_TypeName)) return TT_PointerOrReference; +if (PrevToken->isOneOf(tok::kw_new, tok::kw_delete) && Tok.is(tok::ampamp)) + return TT_BinaryOperator; const FormatToken *NextToken = Tok.getNextNonComment(); diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index da02ced8c7a949..10e0eca62510a7 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -309,6 +309,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) { EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_OverloadedOperatorLParen); EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_FunctionLBrace); EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference); + + Tokens = annotate("if (new && num) {\n" +" new = 1;\n" +"}\n" +"if (!delete && num) {\n" +" delete = 1;\n" +"}"); + ASSERT_EQ(Tokens.size(), 26u) << Tokens; + EXPECT_TOKEN(Tokens[3], tok::ampamp, TT_BinaryOperator); + EXPECT_TOKEN(Tokens[16], tok::ampamp, TT_BinaryOperator); } TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/89016 Reverts commit d68826dfbd98, which changes the previous default behavior of always breaking before a stream insertion operator `<<` if both operands are string literals. Also reverts the related commits 27f547968cce and bf05be5b87fc. See the discussion in #88483. >From 930f422681b3a4f248afc094d3af98952cd7d386 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Tue, 16 Apr 2024 20:51:45 -0700 Subject: [PATCH] [clang-format] Revert breaking stream operators to previous default Reverts commit d68826dfbd98, which changes the previous default behavior of always breaking before a stream insertion operator `<<` if both operands are string literals. Also reverts the related commits 27f547968cce and bf05be5b87fc. See the discussion in #88483. --- clang/lib/Format/TokenAnnotator.cpp | 8 ++-- clang/unittests/Format/FormatTest.cpp | 7 +-- clang/unittests/Format/TokenAnnotatorTest.cpp | 9 - polly/lib/Analysis/DependenceInfo.cpp | 4 ++-- polly/lib/Analysis/ScopBuilder.cpp| 7 --- 5 files changed, 9 insertions(+), 26 deletions(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 628f70417866c3..80e5605fb5778d 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -5595,12 +5595,8 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, return true; if (Left.IsUnterminatedLiteral) return true; - // FIXME: Breaking after newlines seems useful in general. Turn this into an - // option and recognize more cases like endl etc, and break independent of - // what comes after operator lessless. - if (Right.is(tok::lessless) && Right.Next && - Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && - Left.TokenText.ends_with("\\n\"")) { + if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && + Right.Next->is(tok::string_literal)) { return true; } if (Right.is(TT_RequiresClause)) { diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 4906b3350b5b22..bc61b9c089e922 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -27339,12 +27339,6 @@ TEST_F(FormatTest, PPDirectivesAndCommentsInBracedInit) { getLLVMStyleWithColumns(30)); } -TEST_F(FormatTest, StreamOutputOperator) { - verifyFormat("std::cout << \"foo\" << \"bar\" << baz;"); - verifyFormat("std::cout << \"foo\\n\"\n" - " << \"bar\";"); -} - TEST_F(FormatTest, BreakAdjacentStringLiterals) { constexpr StringRef Code{ "return \"Code\" \"\\0\\52\\26\\55\\55\\0\" \"x013\" \"\\02\\xBA\";"}; @@ -27359,6 +27353,7 @@ TEST_F(FormatTest, BreakAdjacentStringLiterals) { Style.BreakAdjacentStringLiterals = false; verifyFormat(Code, Style); } + } // namespace } // namespace test } // namespace format diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index da02ced8c7a949..a71b6806476956 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -2841,15 +2841,6 @@ TEST_F(TokenAnnotatorTest, BraceKind) { EXPECT_BRACE_KIND(Tokens[16], BK_BracedInit); } -TEST_F(TokenAnnotatorTest, StreamOperator) { - auto Tokens = annotate("\"foo\\n\" << aux << \"foo\\n\" << \"foo\";"); - ASSERT_EQ(Tokens.size(), 9u) << Tokens; - EXPECT_FALSE(Tokens[1]->MustBreakBefore); - EXPECT_FALSE(Tokens[3]->MustBreakBefore); - // Only break between string literals if the former ends with \n. - EXPECT_TRUE(Tokens[5]->MustBreakBefore); -} - TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) { auto Tokens = annotate("auto foo() -> enum En {}"); ASSERT_EQ(Tokens.size(), 10u) << Tokens; diff --git a/polly/lib/Analysis/DependenceInfo.cpp b/polly/lib/Analysis/DependenceInfo.cpp index 9ee004fbac9e53..a530fa7b58fa6e 100644 --- a/polly/lib/Analysis/DependenceInfo.cpp +++ b/polly/lib/Analysis/DependenceInfo.cpp @@ -951,8 +951,8 @@ class DependenceInfoPrinterLegacyPass final : public ScopPass { bool runOnScop(Scop &S) override { DependenceInfo &P = getAnalysis(); -OS << "Printing analysis '" << P.getPassName() << "' for " << "region: '" - << S.getRegion().getNameStr() << "' in function '" +OS << "Printing analysis '" << P.getPassName() << "' for " + << "region: '" << S.getRegion().getNameStr() << "' in function '" << S.getFunction().getName() << "':\n"; P.printScop(OS, S); diff --git a/polly/lib/Analysis/ScopBuilder.cpp b/polly/lib/Analysis/ScopBuilder.cpp index 214e4d360d6bbb..a34f2931527255 100644 --- a/polly/lib/Analysis/ScopBuilder.cpp +++ b/polly/lib/Analysis/ScopBuilder.cpp @@ -2715,9 +2715,10 @@ void ScopBuilder::addUserContext() { if (NameContext != NameUserCon
[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/89016 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
owenca wrote: Please see https://github.com/llvm/llvm-project/issues/88483#issuecomment-2053928993 and Conversation in #69859, which was the first attempt at adding an option for breaking consecutive stream insertion operations. Instead of handling everything specified in https://github.com/llvm/llvm-project/pull/69859#issuecomment-1776064714 in a single patch, we can take a few steps: 1. Handle when to break _before_ `<<`. The current default (since 18.x) is only when the left operand is a string literal ending with a newline and the right operand is a string literal. 2. Handle whether to indent or align after the break. 3. Do the above for breaking breaking _after_ `<<`. (Ditto for stream extraction operations if needed.) For No. 1 above, an `enum` option (e.g. `BreakBeforeStreamInsertionOperator`) with `Leave`, `AfterNewline` (LLVM default), `Always`, and `Never` may be sufficient. @s1Sharp https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't break between string literal operands of << (PR #69871)
owenca wrote: > I wish we'd made this removal an option rather than just removing it, what we > are seeing is reasonably formatted json or xml being streamed out is now > poorly written > > ```c++ > osjson << "{\n" ><<" \"name\": \"value\",\n" ><<" \"key\": \"abc\", \n" ><<" }"; > ``` > > now becomes > > ```c++ > osjson << "{\n" <<" \"name\": \"value\",\n <<" \"key\": \"abc\",\n << "}"; > ``` What version was used? I've just tried clang-format 18.1.3, and it's totally fine: ``` $ cat lessless.cpp osjson << "{\n" << " \"name\": \"value\",\n" << " \"key\": \"abc\", \n" << " }"; $ clang-format -version clang-format version 18.1.3 $ clang-format lessless.cpp | diff lessless.cpp - $ ``` https://github.com/llvm/llvm-project/pull/69871 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in ContinuationIndenter (PR #88414)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/88414 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in ContinuationIndenter (PR #88414)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/88414 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in ContinuationIndenter (PR #88414)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/88414 Commit d06b92391513 caused a regression that breaks after a block comment adjacent to a function paramter that follows. Fixes #86573. >From 2ec43f6dc1fafed9d7fc324eeacfa07133af3abd Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Thu, 11 Apr 2024 09:40:01 -0700 Subject: [PATCH] [clang-format] Fix a regression in ContinuationIndenter Commit d06b92391513 caused a regression that breaks after a block comment adjacent to a function paramter that follows. Fixes #86573. --- clang/lib/Format/ContinuationIndenter.cpp | 8 +++- clang/unittests/Format/FormatTestComments.cpp | 4 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index 700bce35c86839..ad0e2c3c620c32 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -684,7 +684,13 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, // arguments to function calls. We do this by ensuring that either all // arguments (including any lambdas) go on the same line as the function // call, or we break before the first argument. -auto PrevNonComment = Current.getPreviousNonComment(); +const auto *Prev = Current.Previous; +if (!Prev) + return false; +// For example, `/*Newline=*/false`. +if (Prev->is(TT_BlockComment) && Current.SpacesRequiredBefore == 0) + return false; +const auto *PrevNonComment = Current.getPreviousNonComment(); if (!PrevNonComment || PrevNonComment->isNot(tok::l_paren)) return false; if (Current.isOneOf(tok::comment, tok::l_paren, TT_LambdaLSquare)) diff --git a/clang/unittests/Format/FormatTestComments.cpp b/clang/unittests/Format/FormatTestComments.cpp index d705cf34d8af02..d2baace6a7d809 100644 --- a/clang/unittests/Format/FormatTestComments.cpp +++ b/clang/unittests/Format/FormatTestComments.cpp @@ -376,6 +376,10 @@ TEST_F(FormatTestComments, RemovesTrailingWhitespaceOfComments) { TEST_F(FormatTestComments, UnderstandsBlockComments) { verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);"); verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y, /*c=*/::c); }"); + verifyFormat("fo(\n" + "/*qq_=*/move(q), [this, b](bar b) {},\n" + "c);", + getLLVMStyleWithColumns(60)); EXPECT_EQ("f(a, /* Trailing comment for aa... */\n" " b);", format("f(a , \\\n" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Fix test case due to clang-format bug fix (PR #88352)
owenca wrote: @HighCommander4 Thanks! https://github.com/llvm/llvm-project/pull/88352 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Fix test case due to clang-format bug fix (PR #88352)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/88352 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Fix test case due to clang-format bug fix (PR #88352)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/88352 >From a070f07c16ddacc1aaf7591a1f7c129bf6abc90a Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Wed, 10 Apr 2024 21:22:05 -0700 Subject: [PATCH] [clangd] Fix test case due to clang-format bug fix See commit 51f1681424f1. --- clang-tools-extra/clangd/unittests/HoverTests.cpp | 8 ++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp b/clang-tools-extra/clangd/unittests/HoverTests.cpp index 35db757b9c15b5..5ead74748f550c 100644 --- a/clang-tools-extra/clangd/unittests/HoverTests.cpp +++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp @@ -1983,10 +1983,14 @@ TEST(Hover, All) { HI.Kind = index::SymbolKind::Macro; HI.Definition = R"cpp(#define MACRO \ - { return 0; } + { \ +return 0; \ + } // Expands to -{ return 0; })cpp"; +{ + return 0; +})cpp"; }}, { R"cpp(// Forward class declaration ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Fix test case due to clang-format bug fix (PR #88352)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/88352 See commit 51f1681424f1. >From 3ecf27d15646345f43703f5a361bd9766307ebf4 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Wed, 10 Apr 2024 21:22:05 -0700 Subject: [PATCH] [clangd] Fix test case due to clang-format bug fix See commit 51f1681424f1. --- clang-tools-extra/clangd/unittests/HoverTests.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp b/clang-tools-extra/clangd/unittests/HoverTests.cpp index 35db757b9c15b5..45266959802832 100644 --- a/clang-tools-extra/clangd/unittests/HoverTests.cpp +++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp @@ -1986,7 +1986,9 @@ TEST(Hover, All) { { return 0; } // Expands to -{ return 0; })cpp"; + { \ +return 0; \ + })cpp"; }}, { R"cpp(// Forward class declaration ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't merge a short block for SBS_Never (PR #88238)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/88238 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't merge a short block for SBS_Never (PR #88238)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/88238 >From 4122a4f0e189afa7aff1010f0061b4f4d2b2a627 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Wed, 10 Apr 2024 00:03:21 -0700 Subject: [PATCH 1/2] [clang-format] Don't merge a short block for SBS_Never Also fix unit tests. Fixes #87484. --- clang/lib/Format/FormatToken.h| 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 8 +- clang/lib/Format/UnwrappedLineParser.cpp | 7 +- clang/unittests/Format/BracesRemoverTest.cpp | 4 +- clang/unittests/Format/FormatTest.cpp | 84 +++ .../Format/FormatTestMacroExpansion.cpp | 7 +- clang/unittests/Format/TokenAnnotatorTest.cpp | 20 + 7 files changed, 106 insertions(+), 26 deletions(-) diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 48b6a9092a8c09..f651e6228c206d 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -35,6 +35,8 @@ namespace format { TYPE(BinaryOperator) \ TYPE(BitFieldColon) \ TYPE(BlockComment) \ + /* l_brace of a block that is not the body of a (e.g. loop) statement. */ \ + TYPE(BlockLBrace) \ TYPE(BracedListLBrace) \ /* The colon at the end of a case label. */ \ TYPE(CaseLabelColon) \ diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index fb31980ab9f491..4ae54e56331bdc 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -796,8 +796,12 @@ class LineJoiner { } } -if (const auto *LastNonComment = Line.getLastNonComment(); -LastNonComment && LastNonComment->is(tok::l_brace)) { +if (Line.endsWith(tok::l_brace)) { + if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never && + Line.First->is(TT_BlockLBrace)) { +return 0; + } + if (IsSplitBlock && Line.First == Line.Last && I > AnnotatedLines.begin() && (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) { diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index c1f7e2874beb24..603268f771ac52 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -395,9 +395,10 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, ParseDefault(); continue; } - if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin) && - tryToParseBracedList()) { -continue; + if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) { +if (tryToParseBracedList()) + continue; +FormatTok->setFinalizedType(TT_BlockLBrace); } parseBlock(); ++StatementCount; diff --git a/clang/unittests/Format/BracesRemoverTest.cpp b/clang/unittests/Format/BracesRemoverTest.cpp index 5155eefb9e08c9..2e983b887ffcb2 100644 --- a/clang/unittests/Format/BracesRemoverTest.cpp +++ b/clang/unittests/Format/BracesRemoverTest.cpp @@ -209,7 +209,9 @@ TEST_F(BracesRemoverTest, RemoveBraces) { verifyFormat("if (a) {\n" " b;\n" "} else {\n" - " { c; }\n" + " {\n" + "c;\n" + " }\n" "}", Style); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index f312a9e21158a9..4906b3350b5b22 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -52,7 +52,13 @@ TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { } TEST_F(FormatTest, FormatsNestedBlockStatements) { - verifyFormat("{\n {\n{}\n }\n}", "{{{}}}"); + verifyFormat("{\n" + " {\n" + "{\n" + "}\n" + " }\n" + "}", + "{{{}}}"); } TEST_F(FormatTest, FormatsNestedCall) { @@ -5669,7 +5675,10 @@ TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { getLLVMStyleWithColumns(14)); } -TEST_F(FormatTest, LayoutRemainingTokens) { verifyFormat("{}"); } +TEST_F(FormatTest, LayoutRemainingTokens) { + verifyFormat("{\n" + "}"); +} TEST_F(FormatTest, MacroDefinitionInsideStatement) { verifyFormat("int x,\n" @@ -6577,7 +6586,11 @@ TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) { } TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { - verifyFormat("{\n { a #c; }\n}"); + verifyFormat("{\n" + " {\n" +
[clang] [clang-format] Don't merge a short block for SBS_Never (PR #88238)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/88238 Also fix unit tests. Fixes #87484. >From 4122a4f0e189afa7aff1010f0061b4f4d2b2a627 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Wed, 10 Apr 2024 00:03:21 -0700 Subject: [PATCH] [clang-format] Don't merge a short block for SBS_Never Also fix unit tests. Fixes #87484. --- clang/lib/Format/FormatToken.h| 2 + clang/lib/Format/UnwrappedLineFormatter.cpp | 8 +- clang/lib/Format/UnwrappedLineParser.cpp | 7 +- clang/unittests/Format/BracesRemoverTest.cpp | 4 +- clang/unittests/Format/FormatTest.cpp | 84 +++ .../Format/FormatTestMacroExpansion.cpp | 7 +- clang/unittests/Format/TokenAnnotatorTest.cpp | 20 + 7 files changed, 106 insertions(+), 26 deletions(-) diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 48b6a9092a8c09..f651e6228c206d 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -35,6 +35,8 @@ namespace format { TYPE(BinaryOperator) \ TYPE(BitFieldColon) \ TYPE(BlockComment) \ + /* l_brace of a block that is not the body of a (e.g. loop) statement. */ \ + TYPE(BlockLBrace) \ TYPE(BracedListLBrace) \ /* The colon at the end of a case label. */ \ TYPE(CaseLabelColon) \ diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index fb31980ab9f491..4ae54e56331bdc 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -796,8 +796,12 @@ class LineJoiner { } } -if (const auto *LastNonComment = Line.getLastNonComment(); -LastNonComment && LastNonComment->is(tok::l_brace)) { +if (Line.endsWith(tok::l_brace)) { + if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never && + Line.First->is(TT_BlockLBrace)) { +return 0; + } + if (IsSplitBlock && Line.First == Line.Last && I > AnnotatedLines.begin() && (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) { diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index c1f7e2874beb24..603268f771ac52 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -395,9 +395,10 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, ParseDefault(); continue; } - if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin) && - tryToParseBracedList()) { -continue; + if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) { +if (tryToParseBracedList()) + continue; +FormatTok->setFinalizedType(TT_BlockLBrace); } parseBlock(); ++StatementCount; diff --git a/clang/unittests/Format/BracesRemoverTest.cpp b/clang/unittests/Format/BracesRemoverTest.cpp index 5155eefb9e08c9..2e983b887ffcb2 100644 --- a/clang/unittests/Format/BracesRemoverTest.cpp +++ b/clang/unittests/Format/BracesRemoverTest.cpp @@ -209,7 +209,9 @@ TEST_F(BracesRemoverTest, RemoveBraces) { verifyFormat("if (a) {\n" " b;\n" "} else {\n" - " { c; }\n" + " {\n" + "c;\n" + " }\n" "}", Style); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index f312a9e21158a9..4906b3350b5b22 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -52,7 +52,13 @@ TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { } TEST_F(FormatTest, FormatsNestedBlockStatements) { - verifyFormat("{\n {\n{}\n }\n}", "{{{}}}"); + verifyFormat("{\n" + " {\n" + "{\n" + "}\n" + " }\n" + "}", + "{{{}}}"); } TEST_F(FormatTest, FormatsNestedCall) { @@ -5669,7 +5675,10 @@ TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { getLLVMStyleWithColumns(14)); } -TEST_F(FormatTest, LayoutRemainingTokens) { verifyFormat("{}"); } +TEST_F(FormatTest, LayoutRemainingTokens) { + verifyFormat("{\n" + "}"); +} TEST_F(FormatTest, MacroDefinitionInsideStatement) { verifyFormat("int x,\n" @@ -6577,7 +6586,11 @@ TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) { } TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { - verifyFormat("{\n { a #c; }\n}"); + verifyFormat("{\n
[clang] [clang-format] instanceof is a keyword only in Java/JavaScript (PR #88085)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/88085 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5c056b3 - [clang-format] Clean up unit tests from commit 13be0d4a34c4
Author: Owen Pan Date: 2024-04-08T21:20:18-07:00 New Revision: 5c056b32350e834924356b1af78504d261d24e42 URL: https://github.com/llvm/llvm-project/commit/5c056b32350e834924356b1af78504d261d24e42 DIFF: https://github.com/llvm/llvm-project/commit/5c056b32350e834924356b1af78504d261d24e42.diff LOG: [clang-format] Clean up unit tests from commit 13be0d4a34c4 - Use 1-parameter verifyFormat() to verify formatted input in LLVM style. - Pass string literal instead of constructed StringRef to verifyFormat(). - Don't include trailing newlines if not needed. Added: Modified: clang/unittests/Format/FormatTest.cpp Removed: diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 91a8ff11889d6f..71450f433cec88 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -7977,39 +7977,37 @@ TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { } TEST_F(FormatTest, BreakFunctionDefinitionParameters) { - FormatStyle Style = getLLVMStyle(); - EXPECT_FALSE(Style.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) {}\n"; - verifyFormat(StringRef("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) {}\n"), - Input, Style); +"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(StringRef("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) {}\n"), + 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 + + // Test the style where all parameters are on their own lines. Style.AllowAllParametersOfDeclarationOnNextLine = false; Style.BinPackParameters = false; - verifyFormat(StringRef("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) {}\n"), + 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); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] instanceof is a keyword only in Java/JavaScript (PR #88085)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/88085 Fixes #87907. >From 0daef6caaac5d3779cda0d4cbbf9cd2514662b92 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 8 Apr 2024 20:29:26 -0700 Subject: [PATCH] [clang-format] instanceof is a keyword only in Java/JavaScript Fixes #87907. --- clang/lib/Format/TokenAnnotator.cpp | 3 ++- clang/unittests/Format/TokenAnnotatorTest.cpp | 4 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 9abd4282103b7b..628f70417866c3 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -2354,7 +2354,8 @@ class AnnotatingParser { // 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 (Current.is(Keywords.kw_instanceof)) { +if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) && +Current.is(Keywords.kw_instanceof)) { Current.setType(TT_BinaryOperator); } else if (isStartOfName(Current) && (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 5ba5e0fbd16f9e..e46a266ff36915 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1769,6 +1769,10 @@ TEST_F(TokenAnnotatorTest, UnderstandsFunctionDeclarationNames) { EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown); EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_FunctionTypeLParen); + Tokens = annotate("void instanceof();"); + ASSERT_EQ(Tokens.size(), 6u); + EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName); + Tokens = annotate("int iso_time(time_t);"); ASSERT_EQ(Tokens.size(), 7u) << Tokens; EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Remove trailing newlines in TableGen formatting test. (PR #87983)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/87983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
owenca wrote: The polly formatting failure should be ignored as CI is using clang-format 18.1.1 instead of the version built from this patch. https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
@@ -538,16 +538,6 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { if (Style.Language == FormatStyle::LK_Proto) { ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); } else { - // Skip NextTok over preprocessor lines, otherwise we may not - // properly diagnose the block as a braced intializer - // if the comma separator appears after the pp directive. - while (NextTok->is(tok::hash)) { -ScopedMacroState MacroState(*Line, Tokens, NextTok); -do { - NextTok = Tokens->getNextToken(); -} while (NextTok->isNot(tok::eof)); - } owenca wrote: This loop is superfluous due to line 498 above. https://github.com/llvm/llvm-project/pull/87953 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/87953 Also fix unit tests and reformat polly. Fixes #86550. >From 6d0c7e5602a227b1b7310be46553aa689e6a93e7 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 7 Apr 2024 17:27:21 -0700 Subject: [PATCH] [clang-format] Correctly annotate braces in macros Also fix unit tests and reformat polly. Fixes #86550. --- clang/lib/Format/UnwrappedLineParser.cpp | 20 +- clang/unittests/Format/FormatTest.cpp | 9 +++- clang/unittests/Format/TokenAnnotatorTest.cpp | 21 +++ .../lib/Analysis/ScopDetectionDiagnostic.cpp | 2 +- 4 files changed, 36 insertions(+), 16 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index af57b1420c6ede..c1f7e2874beb24 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -538,16 +538,6 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { if (Style.Language == FormatStyle::LK_Proto) { ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); } else { - // Skip NextTok over preprocessor lines, otherwise we may not - // properly diagnose the block as a braced intializer - // if the comma separator appears after the pp directive. - while (NextTok->is(tok::hash)) { -ScopedMacroState MacroState(*Line, Tokens, NextTok); -do { - NextTok = Tokens->getNextToken(); -} while (NextTok->isNot(tok::eof)); - } - // Using OriginalColumn to distinguish between ObjC methods and // binary operators is a bit hacky. bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && @@ -606,6 +596,16 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { NextTok = Tokens->getNextToken(); ProbablyBracedList = NextTok->isNot(tok::l_square); } + + // Cpp macro definition body that is a nonempty braced list or block: + if (IsCpp && Line->InMacroBody && PrevTok != FormatTok && + !FormatTok->Previous && NextTok->is(tok::eof) && + // A statement can end with only `;` (simple statement), a block + // closing brace (compound statement), or `:` (label statement). + // If PrevTok is a block opening brace, Tok ends an empty block. + !PrevTok->isOneOf(tok::semi, BK_Block, tok::colon)) { +ProbablyBracedList = true; + } } if (ProbablyBracedList) { Tok->setBlockKind(BK_BracedInit); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 91a8ff11889d6f..1d8745428009e0 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -1865,6 +1865,13 @@ TEST_F(FormatTest, UnderstandsMacros) { 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) { @@ -11035,7 +11042,7 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) { verifyFormat("some_templated_type"); verifyFormat("#define FOO(typeName, realClass) \\\n" - " { #typeName, foo(new foo(#typeName)) }", + " {#typeName, foo(new foo(#typeName))}", getLLVMStyleWithColumns(60)); } diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 5ba5e0fbd16f9e..251e317c7499cf 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1933,14 +1933,20 @@ TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) { "#Bar \\\n" " }"); ASSERT_EQ(Tokens.size(), 11u) << Tokens; - EXPECT_BRACE_KIND(Tokens[6], BK_Block); - EXPECT_BRACE_KIND(Tokens[9], BK_Block); + EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit); + EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit); Tokens = annotate("#define Foo(Bar) \\\n" " { #Bar }"); ASSERT_EQ(Tokens.size(), 11u) << Tokens; - EXPECT_BRACE_KIND(Tokens[6], BK_Block); - EXPECT_BRACE_KIND(Tokens[9], BK_Block); + EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit); + EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit); + + Tokens = annotate("#define FOO(typeName, realClass) \\\n" +" {#typeName, foo(new foo(#typeName))}"); + ASSERT_EQ(Tokens.size(), 29u) << T
[clang] [clang-format] Added unittest of TableGen formatting w.r.t. block type calculation. (PR #87924)
@@ -290,6 +290,16 @@ TEST_F(FormatTestTableGen, MultiClass) { "}\n"); } +TEST_F(FormatTestTableGen, MultiClassesWithPasteOperator) { + // This is a sensitive example for the handling of the paste operators in + // brace type calculation. + verifyFormat("multiclass MultiClass1 {\n" + " def : Def#x;\n" + " def : Def#y;\n" + "}\n" + "multiclass MultiClass2 { def : Def#x; }\n"); owenca wrote: Do you need the trailing newlines? There are dozens of them in this file. Please remove them if they are not needed. https://github.com/llvm/llvm-project/pull/87924 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource (PR #87868)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/87868 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 684f27d - [clang-format][NFC] Use `is` instead of `getType() ==`
Author: Owen Pan Date: 2024-04-06T01:51:45-07:00 New Revision: 684f27d37a6f1faf546a71bcb784b48c7fc8b7e0 URL: https://github.com/llvm/llvm-project/commit/684f27d37a6f1faf546a71bcb784b48c7fc8b7e0 DIFF: https://github.com/llvm/llvm-project/commit/684f27d37a6f1faf546a71bcb784b48c7fc8b7e0.diff LOG: [clang-format][NFC] Use `is` instead of `getType() ==` Added: Modified: clang/lib/Format/FormatTokenLexer.cpp clang/lib/Format/TokenAnnotator.cpp clang/lib/Format/UnwrappedLineParser.cpp clang/lib/Format/WhitespaceManager.cpp Removed: diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index 036f7e6a4efc1e..f430d3764babeb 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -404,7 +404,7 @@ bool FormatTokenLexer::tryMergeNullishCoalescingEqual() { return false; auto &NullishCoalescing = *(Tokens.end() - 2); auto &Equal = *(Tokens.end() - 1); - if (NullishCoalescing->getType() != TT_NullCoalescingOperator || + if (NullishCoalescing->isNot(TT_NullCoalescingOperator) || Equal->isNot(tok::equal)) { return false; } diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 3e9988d5094554..9abd4282103b7b 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -825,8 +825,7 @@ class AnnotatingParser { Parent->overwriteFixedType(TT_BinaryOperator); } // An arrow after an ObjC method expression is not a lambda arrow. -if (CurrentToken->getType() == TT_ObjCMethodExpr && -CurrentToken->Next && +if (CurrentToken->is(TT_ObjCMethodExpr) && CurrentToken->Next && CurrentToken->Next->is(TT_TrailingReturnArrow)) { CurrentToken->Next->overwriteFixedType(TT_Unknown); } @@ -1563,7 +1562,7 @@ class AnnotatingParser { case tok::l_brace: if (Style.Language == FormatStyle::LK_TextProto) { FormatToken *Previous = Tok->getPreviousNonComment(); -if (Previous && Previous->getType() != TT_DictLiteral) +if (Previous && Previous->isNot(TT_DictLiteral)) Previous->setType(TT_SelectorName); } Scopes.push_back(getScopeType(*Tok)); @@ -1583,7 +1582,7 @@ class AnnotatingParser { Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { Tok->setType(TT_DictLiteral); FormatToken *Previous = Tok->getPreviousNonComment(); - if (Previous && Previous->getType() != TT_DictLiteral) + if (Previous && Previous->isNot(TT_DictLiteral)) Previous->setType(TT_SelectorName); } if (Style.isTableGen()) @@ -4754,8 +4753,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, // Objective-C dictionary literal -> no space before closing brace. return false; } - if (Right.getType() == TT_TrailingAnnotation && - Right.isOneOf(tok::amp, tok::ampamp) && + 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 diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 57d8dbcf3b4c77..6df7cc1c39551d 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -366,9 +366,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, continue; } tok::TokenKind Kind = FormatTok->Tok.getKind(); -if (FormatTok->getType() == TT_MacroBlockBegin) +if (FormatTok->is(TT_MacroBlockBegin)) Kind = tok::l_brace; -else if (FormatTok->getType() == TT_MacroBlockEnd) +else if (FormatTok->is(TT_MacroBlockEnd)) Kind = tok::r_brace; auto ParseDefault = [this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile, @@ -4709,14 +4709,13 @@ void UnwrappedLineParser::readToken(int LevelDifference) { do { FormatTok = Tokens->getNextToken(); assert(FormatTok); -while (FormatTok->getType() == TT_ConflictStart || - FormatTok->getType() == TT_ConflictEnd || - FormatTok->getType() == TT_ConflictAlternative) { - if (FormatTok->getType() == TT_ConflictStart) +while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd, + TT_ConflictAlternative)) { + if (FormatTok->is(TT_ConflictStart)) conditionalCompilationStart(/*Unreachable=*/false); - else if (FormatTok->getType() == TT_ConflictAlternative) + else if (FormatTok->is(TT_ConflictAlternative)) conditionalCompilationAlternative(); - else if (FormatTok->getType() == TT_ConflictEnd) + else if (FormatTok->is(TT_ConflictEnd))
[clang] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource (PR #87868)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/87868 >From 5c614fec2b54c146841a9ef3089dee1a63f72543 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Fri, 5 Apr 2024 22:45:47 -0700 Subject: [PATCH 1/2] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource --- clang/lib/Format/FormatTokenSource.h | 9 + clang/lib/Format/UnwrappedLineParser.cpp | 11 ++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/clang/lib/Format/FormatTokenSource.h b/clang/lib/Format/FormatTokenSource.h index cce19f527a9236..1b7d2820e2c3b8 100644 --- a/clang/lib/Format/FormatTokenSource.h +++ b/clang/lib/Format/FormatTokenSource.h @@ -72,6 +72,15 @@ class FormatTokenSource { // getNextToken() -> a1 // getNextToken() -> a2 virtual FormatToken *insertTokens(ArrayRef Tokens) = 0; + + FormatToken *getNextNonComment() { +FormatToken *Tok; +do { + Tok = getNextToken(); + assert(Tok); +} while (Tok->is(tok::comment)); +return Tok; + } }; class IndexedTokenSource : public FormatTokenSource { diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 57d8dbcf3b4c77..33be39f2f77b0b 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -427,11 +427,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, break; case tok::kw_default: { unsigned StoredPosition = Tokens->getPosition(); - FormatToken *Next; - do { -Next = Tokens->getNextToken(); -assert(Next); - } while (Next->is(tok::comment)); + auto *Next = Tokens->getNextNonComment(); FormatTok = Tokens->setPosition(StoredPosition); if (Next->isNot(tok::colon)) { // default not followed by ':' is not a case label; treat it like @@ -497,10 +493,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { assert(Tok->is(tok::l_brace)); do { -FormatToken *NextTok; -do { - NextTok = Tokens->getNextToken(); -} while (NextTok->is(tok::comment)); +auto *NextTok = Tokens->getNextNonComment(); if (!Line->InMacroBody && !Style.isTableGen()) { // Skip PPDirective lines and comments. >From a7675f4a362ffc52a19c49bdc8016335d36127b6 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 6 Apr 2024 01:38:10 -0700 Subject: [PATCH 2/2] Update FormatTokenSource.h Add `[[nodiscard]]`. --- clang/lib/Format/FormatTokenSource.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Format/FormatTokenSource.h b/clang/lib/Format/FormatTokenSource.h index 1b7d2820e2c3b8..2b93f302d36034 100644 --- a/clang/lib/Format/FormatTokenSource.h +++ b/clang/lib/Format/FormatTokenSource.h @@ -73,7 +73,7 @@ class FormatTokenSource { // getNextToken() -> a2 virtual FormatToken *insertTokens(ArrayRef Tokens) = 0; - FormatToken *getNextNonComment() { + [[nodiscard]] FormatToken *getNextNonComment() { FormatToken *Tok; do { Tok = getNextToken(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource (PR #87868)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/87868 None >From 5c614fec2b54c146841a9ef3089dee1a63f72543 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Fri, 5 Apr 2024 22:45:47 -0700 Subject: [PATCH] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource --- clang/lib/Format/FormatTokenSource.h | 9 + clang/lib/Format/UnwrappedLineParser.cpp | 11 ++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/clang/lib/Format/FormatTokenSource.h b/clang/lib/Format/FormatTokenSource.h index cce19f527a9236..1b7d2820e2c3b8 100644 --- a/clang/lib/Format/FormatTokenSource.h +++ b/clang/lib/Format/FormatTokenSource.h @@ -72,6 +72,15 @@ class FormatTokenSource { // getNextToken() -> a1 // getNextToken() -> a2 virtual FormatToken *insertTokens(ArrayRef Tokens) = 0; + + FormatToken *getNextNonComment() { +FormatToken *Tok; +do { + Tok = getNextToken(); + assert(Tok); +} while (Tok->is(tok::comment)); +return Tok; + } }; class IndexedTokenSource : public FormatTokenSource { diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 57d8dbcf3b4c77..33be39f2f77b0b 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -427,11 +427,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, break; case tok::kw_default: { unsigned StoredPosition = Tokens->getPosition(); - FormatToken *Next; - do { -Next = Tokens->getNextToken(); -assert(Next); - } while (Next->is(tok::comment)); + auto *Next = Tokens->getNextNonComment(); FormatTok = Tokens->setPosition(StoredPosition); if (Next->isNot(tok::colon)) { // default not followed by ':' is not a case label; treat it like @@ -497,10 +493,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { assert(Tok->is(tok::l_brace)); do { -FormatToken *NextTok; -do { - NextTok = Tokens->getNextToken(); -} while (NextTok->is(tok::comment)); +auto *NextTok = Tokens->getNextNonComment(); if (!Line->InMacroBody && !Style.isTableGen()) { // Skip PPDirective lines and comments. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 7702023 - [clang-format][NFC] Rename `kind` to `Kind`
Author: Owen Pan Date: 2024-04-05T22:17:50-07:00 New Revision: 770202343ebce1f2bc0745c78e298e251f204bee URL: https://github.com/llvm/llvm-project/commit/770202343ebce1f2bc0745c78e298e251f204bee DIFF: https://github.com/llvm/llvm-project/commit/770202343ebce1f2bc0745c78e298e251f204bee.diff LOG: [clang-format][NFC] Rename `kind` to `Kind` Added: Modified: clang/lib/Format/UnwrappedLineParser.cpp Removed: diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 55c627d87f08b5..57d8dbcf3b4c77 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -365,11 +365,11 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, nextToken(); continue; } -tok::TokenKind kind = FormatTok->Tok.getKind(); +tok::TokenKind Kind = FormatTok->Tok.getKind(); if (FormatTok->getType() == TT_MacroBlockBegin) - kind = tok::l_brace; + Kind = tok::l_brace; else if (FormatTok->getType() == TT_MacroBlockEnd) - kind = tok::r_brace; + Kind = tok::r_brace; auto ParseDefault = [this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile, &HasLabel, &StatementCount] { @@ -380,7 +380,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, assert(StatementCount > 0 && "StatementCount overflow!"); }; -switch (kind) { +switch (Kind) { case tok::comment: nextToken(); addUnwrappedLine(); @@ -3280,8 +3280,8 @@ void UnwrappedLineParser::parseSwitch() { } // Operators that can follow a C variable. -static bool isCOperatorFollowingVar(tok::TokenKind kind) { - switch (kind) { +static bool isCOperatorFollowingVar(tok::TokenKind Kind) { + switch (Kind) { case tok::ampamp: case tok::ampequal: case tok::arrow: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate block braces of empty ctors/dtors (PR #82097)
owenca wrote: /cherry-pick 8de230093f58 https://github.com/llvm/llvm-project/pull/82097 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating BK_BracedInit (PR #87450)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/87450 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating BK_BracedInit (PR #87450)
https://github.com/owenca dismissed https://github.com/llvm/llvm-project/pull/87450 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [polly] [clang-format] Correctly annotate block braces of empty ctors/dtors (PR #82097)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/82097 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating TrailingReturnArrow (PR #86624)
owenca wrote: Ping @mydeveloperday @HazardyKnusperkeks @rymiel https://github.com/llvm/llvm-project/pull/86624 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Lambda parameter should be passed by const reference (PR #87306)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/87306 Closes #87254. >From 91edc2bff0ea98e39b5614ae91ab562c1135b6e7 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 1 Apr 2024 20:08:21 -0700 Subject: [PATCH] [clang-format] Lambda parameter should be passed by const reference Closes #87254. --- clang/lib/Format/Format.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 46ed5baaeacead..1a45d5089e209c 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3578,7 +3578,7 @@ cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, // We need to use lambda function here since there are two versions of // `cleanup`. auto Cleanup = [](const FormatStyle &Style, StringRef Code, -std::vector Ranges, +const std::vector &Ranges, StringRef FileName) -> tooling::Replacements { return cleanup(Style, Code, Ranges, FileName); }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating TrailingReturnArrow (PR #86624)
https://github.com/owenca milestoned https://github.com/llvm/llvm-project/pull/86624 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Exit clang-format-diff only after all diffs are printed (PR #86776)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/86776 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Exit clang-format-diff only after all diffs are printed (PR #86776)
https://github.com/owenca edited https://github.com/llvm/llvm-project/pull/86776 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ability for clang-format-diff to exit with non-0 status (PR #70883)
owenca wrote: See #86776. https://github.com/llvm/llvm-project/pull/70883 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Exit clang-format-diff only after all diffs are printed (PR #86776)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/86776 None >From 216681ceb6346b56e8013935b2d3938bde5039ea Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Tue, 26 Mar 2024 23:27:51 -0700 Subject: [PATCH] [clang-format] Exit clang-format-diff only after all diffs are printed --- clang/tools/clang-format/clang-format-diff.py | 10 +++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/clang/tools/clang-format/clang-format-diff.py b/clang/tools/clang-format/clang-format-diff.py index 0a2c24743678d0..3a74b90e731578 100755 --- a/clang/tools/clang-format/clang-format-diff.py +++ b/clang/tools/clang-format/clang-format-diff.py @@ -138,6 +138,7 @@ def main(): ) # Reformat files containing changes in place. +has_diff = False for filename, lines in lines_by_file.items(): if args.i and args.verbose: print("Formatting {}".format(filename)) @@ -169,7 +170,7 @@ def main(): stdout, stderr = p.communicate() if p.returncode != 0: -sys.exit(p.returncode) +return p.returncode if not args.i: with open(filename) as f: @@ -185,9 +186,12 @@ def main(): ) diff_string = "".join(diff) if len(diff_string) > 0: +has_diff = True sys.stdout.write(diff_string) -sys.exit(1) + +if has_diff: +return 1 if __name__ == "__main__": -main() +sys.exit(main()) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
@@ -4827,6 +4827,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } +if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && +Right.TokenText[0] == '.') { owenca wrote: I suppose a `numeric_constant` can't follow an `identifier` except when they're inside attributes. clang-format is allowed to remove spaces between any two tokens only if they won't be changed to a single token. That's why we can remove the space in `type .5` but not `type 5`. https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a regression in annotating TrailingReturnArrow (PR #86624)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/86624 Fixes #86559. >From 5ba6a0adcf9de7035dd195f0b83ada39019b7e12 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 25 Mar 2024 21:13:04 -0700 Subject: [PATCH] [clang-format] Fix a regression in annotating TrailingReturnArrow Fixes #86559. --- clang/lib/Format/TokenAnnotator.cpp | 2 ++ clang/unittests/Format/TokenAnnotatorTest.cpp | 4 2 files changed, 6 insertions(+) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 4c83a7a3a323be..dd167b07f83453 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -3888,6 +3888,8 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const { } } else if (ClosingParen) { for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) { +if (Tok->is(TT_CtorInitializerColon)) + break; if (Tok->is(tok::arrow)) { Tok->setType(TT_TrailingReturnArrow); break; diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 2539d3d76ef019..9425647d99980b 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1916,6 +1916,10 @@ TEST_F(TokenAnnotatorTest, UnderstandsTrailingReturnArrow) { ASSERT_EQ(Tokens.size(), 12u) << Tokens; EXPECT_TOKEN(Tokens[7], tok::arrow, TT_Unknown); + Tokens = annotate("__attribute__((cold)) C() : Base(obj->func()) {}"); + ASSERT_EQ(Tokens.size(), 21u) << Tokens; + EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown); + // Mixed Tokens = annotate("auto f() -> int { auto a = b()->c; }"); ASSERT_EQ(Tokens.size(), 18u) << Tokens; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
@@ -4827,6 +4827,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } +if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && +Right.TokenText[0] == '.') { owenca wrote: Yes, or else `type 5` would be merged into a single token `type5`. https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits