New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
clang-format: SpacesInSquareBrackets does not work properly for Java #77740
Comments
This was still an issue with 17 |
@llvm/issue-subscribers-bug Author: Miki (mikir)
The following Java snippet
using the following clang-format configuration
is formatted as
We are using clang-format Ubuntu clang-format version 14.0.0-1ubuntu1.1. |
small repo public static void foo()
{
auto types = new A[numElements];
auto types = new Class<T>[ numElements ];
} |
Workaround Add SpacesInContainerLiterals: false |
So I do think this is missing code (which is handled in C#) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 73840332e22c..86e9ed931f7c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4472,6 +4472,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
} else if (Style.Language == FormatStyle::LK_Java) {
if (Left.is(tok::r_square) && Right.is(tok::l_brace))
return true;
+ // spaces inside square brackets.
+ if (Left.is(tok::l_square) || Right.is(tok::r_square))
+ return Style.SpacesInSquareBrackets;
+
if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) {
return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTestJava.cpp b/clang/unittests/Format/FormatTestJava.cpp
index 51afe79859ec..6bb4b0013eeb 100644
--- a/clang/unittests/Format/FormatTestJava.cpp
+++ b/clang/unittests/Format/FormatTestJava.cpp
@@ -625,5 +625,20 @@ TEST_F(FormatTestJava, ShortFunctions) {
Style);
}
+TEST_F(FormatTestJava, ConfigurableSpacesInSquareBrackets) {
+ FormatStyle Spaces = getLLVMStyle(FormatStyle::LK_Java);
+
+ verifyFormat("Object[] arguments", Spaces);
+ verifyFormat("final Class<?>[] types = new Class<?>[numElements];", Spaces);
+ verifyFormat("types[i] = arguments[i].getClass();", Spaces);
+
+ Spaces.SpacesInSquareBrackets = true;
+
+ verifyFormat("Object[ ] arguments", Spaces);
+ verifyFormat("final Class<?>[ ] types = new Class<?>[ numElements ];",
+ Spaces);
+ verifyFormat("types[ i ] = arguments[ i ].getClass();", Spaces);
+}
+
} // namespace format
} // end namespace clang |
Thanks a lot for your quick response and especially for this workaround. It helped. |
A fix for this has landed in main and should form part of the 18.X release |
The following Java snippet
using the following clang-format configuration
is formatted as
We are using clang-format Ubuntu clang-format version 14.0.0-1ubuntu1.1.
The text was updated successfully, but these errors were encountered: