Skip to content

Commit 4133c0b

Browse files
homberghpmbien
authored andcommitted
solves apache#7043, formatting error of closing brace in record definition
adds tests to show the error adds inner and outer record in ui template text for setting java format spaces solves the error by moving spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true); to the correct place. solves apache#7043 formatter to handle record closing braces correctly squashed commits of test and solution.
1 parent 59bea23 commit 4133c0b

File tree

3 files changed

+199
-4
lines changed

3 files changed

+199
-4
lines changed

java/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -947,7 +947,7 @@ public Boolean visitClass(ClassTree node, Void p) {
947947
}
948948
List<? extends Tree> perms = node.getPermitsClause();
949949
if (perms != null && !perms.isEmpty()) {
950-
wrapToken(cs.wrapExtendsImplementsKeyword(), 1, EXTENDS);
950+
wrapToken(cs.wrapExtendsImplementsKeyword(), 1, EXTENDS);
951951
wrapList(cs.wrapExtendsImplementsList(), cs.alignMultilineImplements(), true, COMMA, perms);
952952
}
953953
} finally {
@@ -1352,6 +1352,7 @@ private Boolean scanRecord(ClassTree node, Void p) {
13521352
if (!recParams.isEmpty()) {
13531353
spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true);
13541354
wrapList(cs.wrapMethodParams(), cs.alignMultilineMethodParams(), false, COMMA, recParams);
1355+
spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true); // solves #7403
13551356
}
13561357
accept(RPAREN);
13571358
List<? extends Tree> impls = node.getImplementsClause();
@@ -1398,8 +1399,6 @@ private Boolean scanRecord(ClassTree node, Void p) {
13981399
isFirstMember = false;
13991400
}
14001401
}
1401-
1402-
spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true);
14031402
}
14041403
} finally {
14051404
indent = oldIndent;
@@ -5425,7 +5424,7 @@ private void reformatComment() {
54255424
}
54265425

54275426
/**
5428-
*
5427+
*
54295428
* @see <a href="https://docs.oracle.com/en/java/javase/22/docs/specs/javadoc/doc-comment-spec.html#Where%20Tags%20Can%20Be%20Used">for more info on inline tags check documentation here.</a>
54305429
* @return returns true if has inline tag prefix like "{+@tagname"
54315430
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.netbeans.modules.java.source.save;
20+
21+
import java.io.File;
22+
import java.util.ArrayList;
23+
import java.util.List;
24+
import java.util.prefs.Preferences;
25+
import javax.lang.model.SourceVersion;
26+
import javax.swing.JEditorPane;
27+
import javax.swing.text.Document;
28+
import static junit.framework.TestCase.assertEquals;
29+
import static junit.framework.TestCase.fail;
30+
import org.netbeans.api.editor.mimelookup.MimeLookup;
31+
import org.netbeans.api.java.classpath.ClassPath;
32+
import org.netbeans.api.java.lexer.JavaTokenId;
33+
import org.netbeans.api.java.source.SourceUtilsTestUtil;
34+
import org.netbeans.api.java.source.TestUtilities;
35+
import org.netbeans.api.lexer.Language;
36+
import org.netbeans.junit.NbTestCase;
37+
import org.netbeans.junit.NbTestSuite;
38+
import org.netbeans.modules.editor.indent.api.Reformat;
39+
import org.netbeans.modules.java.source.BootClassPathUtil;
40+
import org.netbeans.modules.java.source.usages.IndexUtil;
41+
import org.netbeans.spi.java.classpath.ClassPathProvider;
42+
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
43+
import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
44+
import org.openide.cookies.EditorCookie;
45+
import org.openide.filesystems.FileObject;
46+
import org.openide.filesystems.FileUtil;
47+
import org.openide.loaders.DataObject;
48+
import org.openide.util.SharedClassObject;
49+
50+
/**
51+
* Test to show the problem mentioned in #7043.
52+
*
53+
* For some strange reason, the setting spaceWithinMethodDeclParens affects the
54+
* formatting (indentation) of the trailing brace (}) of a record definition,
55+
* both as inner record and as top level record.
56+
*
57+
* @author homberghp
58+
*/
59+
public class RecordFormattingTest extends NbTestCase {
60+
61+
File testFile = null;
62+
private String sourceLevel = "1.8";
63+
private static final List<String> EXTRA_OPTIONS = new ArrayList<>();
64+
65+
/**
66+
* Creates a new instance of FormatingTest
67+
*/
68+
public RecordFormattingTest(String name) {
69+
super(name);
70+
}
71+
72+
public static NbTestSuite suite() {
73+
NbTestSuite suite = new NbTestSuite();
74+
suite.addTestSuite(RecordFormattingTest.class);
75+
return suite;
76+
}
77+
78+
String content
79+
= """
80+
record Student(int id,String lastname,String firstname) implements Serializable {
81+
int m(int x){
82+
return id+x;
83+
}
84+
} // should stay flush to left margin
85+
""";
86+
87+
public void test7043NoSpaces() throws Exception {
88+
run7043("""
89+
record Student(int id, String lastname, String firstname) implements Serializable {
90+
int m(int x) {
91+
return id + x;
92+
}
93+
} // should stay flush to left margin
94+
""", false);
95+
}
96+
97+
public void test7043WithSpaces() throws Exception {
98+
run7043("""
99+
record Student( int id, String lastname, String firstname ) implements Serializable {
100+
int m( int x ) {
101+
return id + x;
102+
}
103+
} // should stay flush to left margin
104+
""", true);
105+
}
106+
107+
/**
108+
* The java formatter indents the final brace '}' of a record to far to the
109+
* right, when the setting spaceWithinMethodDeclParens is True AND the
110+
* record header defines parameters. This
111+
*
112+
* @throws Exception for some reason
113+
*/
114+
// copied from testSealed
115+
public void run7043(String golden, boolean spacesInMethodDecl) throws Exception {
116+
try {
117+
SourceVersion.valueOf("RELEASE_17"); //NOI18N
118+
} catch (IllegalArgumentException ex) {
119+
//OK, no RELEASE_15, skip test
120+
return;
121+
}
122+
testFile = new File(getWorkDir(), "Test.java");
123+
TestUtilities.copyStringToFile(testFile, "");
124+
FileObject testSourceFO = FileUtil.toFileObject(testFile);
125+
DataObject testSourceDO = DataObject.find(testSourceFO);
126+
EditorCookie ec = (EditorCookie)testSourceDO.getCookie(EditorCookie.class);
127+
Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class);
128+
preferences.putBoolean("spaceWithinMethodDeclParens", spacesInMethodDecl);
129+
preferences.putInt("blankLinesAfterClassHeader", 0);
130+
131+
final Document doc = ec.openDocument();
132+
doc.putProperty(Language.class, JavaTokenId.language());
133+
reformat(doc, content, golden);
134+
}
135+
136+
private void reformat(Document doc, String content, String golden) throws Exception {
137+
reformat(doc, content, golden, 0, content.length());
138+
}
139+
140+
private void reformat(Document doc, String content, String golden, int startOffset, int endOffset) throws Exception {
141+
doc.remove(0, doc.getLength());
142+
doc.insertString(0, content, null);
143+
144+
Reformat reformat = Reformat.get(doc);
145+
reformat.lock();
146+
try {
147+
reformat.reformat(startOffset, endOffset);
148+
} finally {
149+
reformat.unlock();
150+
}
151+
String res = doc.getText(0, doc.getLength());
152+
assertNoDiff(golden, res);
153+
}
154+
155+
static void assertNoDiff(String expected, String actual) {
156+
var expectedLines = expected.trim().split("\n");
157+
var actualLines = actual.trim().split("\n");
158+
// fail if not of equal length
159+
String assertResult = "";
160+
if (expectedLines.length != actualLines.length) {
161+
assertResult
162+
= "number of lines differ :\n expected nr of lines = " + expectedLines.length
163+
+ " actual nr of lines= " + actualLines.length;
164+
}
165+
166+
for (int i = 0; i < expectedLines.length && i < actualLines.length; i++) {
167+
String actualLine = actualLines[i];
168+
String expLine = expectedLines[i];
169+
if (expLine.equals(actualLine)) {
170+
continue;
171+
}
172+
assertResult += "\n expected at line " + (i + 1) + ": \n'" + expLine + "'\n not equal to actual \n'" + actualLine + "'";
173+
}
174+
if (assertResult.equals("")) {
175+
return;
176+
}
177+
// output generated only when test fails, to help finding the difference.
178+
for (int i = 1; i <= expectedLines.length; i++) {
179+
String line = expectedLines[i-1];
180+
System.err.format("%3d: %s\n", i,line);
181+
182+
}
183+
System.err.println("actual");
184+
for (int i = 1; i <= actualLines.length; i++) {
185+
String line = actualLines[i-1];
186+
System.err.format("%3d: %s\n", i,line);
187+
}
188+
fail("not golden, see stderr for more info");
189+
190+
}
191+
192+
}

java/java.source/src/org/netbeans/modules/java/ui/Bundle.properties

+4
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,10 @@ default\:\
497497
public int add(int a, int b) {\
498498
return a + b;\
499499
}\
500+
public record ARecord(String name, int age){\
501+
}\
502+
}\
503+
record TopLevelRecord(String name, double value){\
500504
}
501505

502506
#do not translate

0 commit comments

Comments
 (0)