diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java index 0cdf79d497..399cfc55ef 100644 --- a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java @@ -1,9 +1,10 @@ package com.github.javaparser.generator.core; +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; import com.github.javaparser.generator.core.node.*; import com.github.javaparser.generator.core.visitor.*; -import com.github.javaparser.printer.PrettyPrinter; -import com.github.javaparser.printer.PrettyPrinterConfiguration; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; import com.github.javaparser.utils.SourceRoot; import java.nio.file.Path; @@ -18,8 +19,13 @@ public static void main(String[] args) throws Exception { throw new RuntimeException("Need 1 parameter: the JavaParser source checkout root directory."); } final Path root = Paths.get(args[0], "..", "javaparser-core", "src", "main", "java"); - final SourceRoot sourceRoot = new SourceRoot(root); - sourceRoot.setPrinter(new PrettyPrinter(new PrettyPrinterConfiguration().setEndOfLineCharacter("\n"))::print); + final SourceRoot sourceRoot = new SourceRoot(root) + .setPrinter(LexicalPreservingPrinter::print) + .setJavaParser(new JavaParser( + new ParserConfiguration() + .setStoreTokens(false) + .setAttributeComments(false) + .setLexicalPreservationEnabled(true))); new CoreGenerator().run(sourceRoot); diff --git a/javaparser-core/src/main/java/com/github/javaparser/JavaParser.java b/javaparser-core/src/main/java/com/github/javaparser/JavaParser.java index e3e74d1c3b..a3ce9067fc 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/JavaParser.java +++ b/javaparser-core/src/main/java/com/github/javaparser/JavaParser.java @@ -39,6 +39,7 @@ import com.github.javaparser.ast.type.Type; import com.github.javaparser.ast.validator.ProblemReporter; import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; import java.io.*; import java.nio.charset.Charset; @@ -135,6 +136,9 @@ public ParseResult parse(ParseStart start, Provider provi final CommentsCollection comments = parser.getCommentsCollection(); commentsInserter.insertComments(resultNode, comments.copy().getComments()); } + if(configuration.isLexicalPreservationEnabled()){ + LexicalPreservingPrinter.setup(resultNode); + } configuration.getValidator().accept(resultNode, new ProblemReporter(parser.problems)); parser.problems.sort(PROBLEM_BY_BEGIN_POSITION); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ParserConfiguration.java b/javaparser-core/src/main/java/com/github/javaparser/ParserConfiguration.java index 0f8afa5bad..d73451fe61 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ParserConfiguration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ParserConfiguration.java @@ -37,6 +37,7 @@ public class ParserConfiguration { private boolean attributeComments = true; private boolean doNotAssignCommentsPrecedingEmptyLines = true; private boolean doNotConsiderAnnotationsAsNodeStartForCodeAttribution = false; + private boolean lexicalPreservationEnabled = false; private int tabSize = 1; private Validator validator = new Java8Validator(); @@ -106,4 +107,18 @@ public ParserConfiguration setValidator(Validator validator) { this.validator = validator; return this; } + + /** + * Disabled by default. + * When this is enabled, LexicalPreservingPrinter.print can be used to reproduce + * the original formatting of the file. + */ + public ParserConfiguration setLexicalPreservationEnabled(boolean lexicalPreservationEnabled) { + this.lexicalPreservationEnabled = lexicalPreservationEnabled; + return this; + } + + public boolean isLexicalPreservationEnabled() { + return lexicalPreservationEnabled; + } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index 75efc815eb..53a9e2f2c1 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -86,11 +86,21 @@ public static Pair, LexicalPreservingPrinter> se return new Pair<>(parseResult, lexicalPreservingPrinter); } - public static void setup(Node node) { + /** + * Prepares the node so it can be used in the print methods. + * The correct order is: + *
    + *
  1. Parse some code
  2. + *
  3. Call this setup method on the result
  4. + *
  5. Make changes to the AST as desired
  6. + *
  7. Use one of the print methods on this class to print out the original source code with your changes added
  8. + *
+ * @return the node passed as a parameter for your convenience. + */ + public static N setup(N node) { assertNotNull(node); node.getTokenRange().ifPresent(r -> { - // Store initial text storeInitialText(node); // Setup observer @@ -98,6 +108,7 @@ public static void setup(Node node) { node.registerForSubtree(observer); }); + return node; } // diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java index f32037f399..a7ca65efb5 100644 --- a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java @@ -21,13 +21,10 @@ package com.github.javaparser.printer.lexicalpreservation; -import com.github.javaparser.ParseResult; -import com.github.javaparser.ParseStart; -import com.github.javaparser.Providers; +import com.github.javaparser.JavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.expr.Expression; -import com.github.javaparser.utils.Pair; import org.junit.Before; import java.io.IOException; @@ -37,28 +34,20 @@ public abstract class AbstractLexicalPreservingTest { - protected LexicalPreservingPrinter lpp; protected CompilationUnit cu; protected Expression expression; @Before public void setup() { - lpp = null; cu = null; } protected void considerCode(String code) { - Pair, LexicalPreservingPrinter> res = LexicalPreservingPrinter.setup( - ParseStart.COMPILATION_UNIT, Providers.provider(code)); - cu = res.a.getResult().get(); - lpp = res.b; + cu = LexicalPreservingPrinter.setup(JavaParser.parse(code)); } protected void considerExpression(String code) { - Pair, LexicalPreservingPrinter> res = LexicalPreservingPrinter.setup( - ParseStart.EXPRESSION, Providers.provider(code)); - expression = res.a.getResult().get(); - lpp = res.b; + expression = LexicalPreservingPrinter.setup(JavaParser.parseExpression(code)); } protected String considerExample(String resourceName) throws IOException { @@ -73,17 +62,17 @@ protected String readExample(String resourceName) throws IOException { protected void assertTransformed(String exampleName, Node node) throws IOException { String expectedCode = readExample(exampleName + "_expected"); - String actualCode = lpp.print(node); + String actualCode = LexicalPreservingPrinter.print(node); assertEquals(expectedCode, actualCode); } protected void assertUnchanged(String exampleName) throws IOException { String code = considerExample(exampleName + "_original"); - assertEquals(code, lpp.print(cu != null ? cu : expression)); + assertEquals(code, LexicalPreservingPrinter.print(cu != null ? cu : expression)); } protected void assertTransformedToString(String expectedPartialCode, Node node) { - String actualCode = lpp.print(node); + String actualCode = LexicalPreservingPrinter.print(node); assertEquals(expectedPartialCode, actualCode); } diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java index 3c31ee6e98..00e778d717 100644 --- a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java @@ -9,7 +9,6 @@ import com.github.javaparser.ast.type.UnionType; import com.github.javaparser.ast.type.VoidType; import com.github.javaparser.ast.visitor.ModifierVisitor; -import com.github.javaparser.utils.Pair; import org.junit.Test; import java.io.IOException; @@ -23,8 +22,7 @@ import static org.junit.Assert.assertTrue; public class LexicalPreservingPrinterTest extends AbstractLexicalPreservingTest { - // Visible for testing - NodeText getTextForNode(Node node) { + private NodeText getTextForNode(Node node) { return node.getData(NODE_TEXT_DATA); } @@ -63,7 +61,7 @@ public void checkNodeTextCreatedForField() { ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); FieldDeclaration fd = classA.getFieldByName("i").get(); - NodeText nodeText = lpp.getOrCreateNodeText(fd); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(fd); assertEquals(Arrays.asList("int", " ", "i", ";"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -76,7 +74,7 @@ public void checkNodeTextCreatedForVariableDeclarator() { ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); FieldDeclaration fd = classA.getFieldByName("i").get(); VariableDeclarator vd = fd.getVariables().get(0); - NodeText nodeText = lpp.getOrCreateNodeText(vd); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(vd); assertEquals(Arrays.asList("i"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -88,7 +86,7 @@ public void checkNodeTextCreatedForMethod() { ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); MethodDeclaration md = classA.getMethodsByName("foo").get(0); - NodeText nodeText = lpp.getOrCreateNodeText(md); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); assertEquals(Arrays.asList("void", " ", "foo", "(", "int p1", ",", " ", "float p2", ")", " ", "{ }"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -101,7 +99,7 @@ public void checkNodeTextCreatedForMethodParameter() { ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); MethodDeclaration md = classA.getMethodsByName("foo").get(0); Parameter p1 = md.getParameterByName("p1").get(); - NodeText nodeText = lpp.getOrCreateNodeText(p1); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(p1); assertEquals(Arrays.asList("int", " ", "p1"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -115,7 +113,7 @@ public void checkNodeTextCreatedForPrimitiveType() { MethodDeclaration md = classA.getMethodsByName("foo").get(0); Parameter p1 = md.getParameterByName("p1").get(); Type t = p1.getType(); - NodeText nodeText = lpp.getOrCreateNodeText(t); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(t); assertEquals(Arrays.asList("int"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -126,7 +124,7 @@ public void checkNodeTextCreatedForSimpleImport() { considerCode(code); ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); - NodeText nodeText = lpp.getOrCreateNodeText(imp); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(imp); assertEquals(Arrays.asList("import", " ", "a.b.c.D", ";", ""), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -139,7 +137,7 @@ public void checkNodeTextCreatedGenericType() { FieldDeclaration field = cu.getClassByName("A").get().getFieldByName("result").get(); Node t = field.getCommonType(); Node t2 = field.getVariable(0).getType(); - NodeText nodeText = lpp.getOrCreateNodeText(field); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(field); assertEquals(Arrays.asList("ParseResult", "<", "T", ">", " ", "result", ";"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -150,7 +148,7 @@ public void checkNodeTextCreatedAnnotationDeclaration() { considerCode(code); AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); - NodeText nodeText = lpp.getOrCreateNodeText(ad); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(ad); assertEquals(Arrays.asList("public", " ", "@", "interface", " ", "ClassPreamble", " ", "{", " ", "String author();", " ", "}", ""), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -162,7 +160,7 @@ public void checkNodeTextCreatedAnnotationMemberDeclaration() { AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0); - NodeText nodeText = lpp.getOrCreateNodeText(md); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); assertEquals(Arrays.asList("String", " ", "author", "(", ")", ";"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -174,7 +172,7 @@ public void checkNodeTextCreatedAnnotationMemberDeclarationWithArrayType() { AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0); - NodeText nodeText = lpp.getOrCreateNodeText(md); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); assertEquals(Arrays.asList("String[]", " ", "author", "(", ")", ";"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -187,7 +185,7 @@ public void checkNodeTextCreatedAnnotationMemberDeclarationArrayType() { AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0); Type type = md.getType(); - NodeText nodeText = lpp.getOrCreateNodeText(type); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(type); assertEquals(Arrays.asList("String", "[", "]"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -197,7 +195,7 @@ public void checkNodeTextCreatedAnnotationMemberDeclarationWithComment() throws considerExample("AnnotationDeclaration_Example3_original"); AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5); - NodeText nodeText = lpp.getOrCreateNodeText(md); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); assertEquals(Arrays.asList("String[]", " ", "reviewers", "(", ")", ";"), nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); } @@ -208,7 +206,7 @@ public void checkNodeTextCreatedArrayCreationLevelWithoutExpression() throws IOE ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)expression; ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); - NodeText nodeText = lpp.getOrCreateNodeText(arrayCreationLevel); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); assertEquals(Arrays.asList("[", "]"), nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()).collect(Collectors.toList())); } @@ -219,7 +217,7 @@ public void checkNodeTextCreatedArrayCreationLevelWith() throws IOException { ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)expression; ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); - NodeText nodeText = lpp.getOrCreateNodeText(arrayCreationLevel); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); assertEquals(Arrays.asList("[", "123", "]"), nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()).collect(Collectors.toList())); } @@ -232,7 +230,7 @@ public void checkNodeTextCreatedArrayCreationLevelWith() throws IOException { public void findIndentationForAnnotationMemberDeclarationWithoutComment() throws IOException { considerExample("AnnotationDeclaration_Example3_original"); Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(4); - List indentation = lpp.findIndentation(node); + List indentation = LexicalPreservingPrinter.findIndentation(node); assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList())); } @@ -240,7 +238,7 @@ public void findIndentationForAnnotationMemberDeclarationWithoutComment() throws public void findIndentationForAnnotationMemberDeclarationWithComment() throws IOException { considerExample("AnnotationDeclaration_Example3_original"); Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5); - List indentation = lpp.findIndentation(node); + List indentation = LexicalPreservingPrinter.findIndentation(node); assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList())); } @@ -253,7 +251,7 @@ public void printASuperSimpleCUWithoutChanges() { String code = "class A {}"; considerCode(code); - assertEquals(code, lpp.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu)); } @Test @@ -263,7 +261,7 @@ public void printASuperSimpleClassWithAFieldAdded() { ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); classA.addField("int", "myField"); - assertEquals("class A {" + EOL + " int myField;"+EOL+"}", lpp.print(classA)); + assertEquals("class A {" + EOL + " int myField;"+EOL+"}", LexicalPreservingPrinter.print(classA)); } @Test @@ -271,7 +269,7 @@ public void printASuperSimpleClassWithoutChanges() { String code = "class A {}"; considerCode(code); - assertEquals(code, lpp.print(cu.getClassByName("A").get())); + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); } @Test @@ -279,9 +277,9 @@ public void printASimpleCUWithoutChanges() { String code = "class /*a comment*/ A {\t\t"+EOL+" int f;"+EOL+EOL+EOL+" void foo(int p ) { return 'z' \t; }}"; considerCode(code); - assertEquals(code, lpp.print(cu)); - assertEquals(code, lpp.print(cu.getClassByName("A").get())); - assertEquals("void foo(int p ) { return 'z' \t; }", lpp.print(cu.getClassByName("A").get().getMethodsByName("foo").get(0))); + assertEquals(code, LexicalPreservingPrinter.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); + assertEquals("void foo(int p ) { return 'z' \t; }", LexicalPreservingPrinter.print(cu.getClassByName("A").get().getMethodsByName("foo").get(0))); } @Test @@ -293,7 +291,7 @@ public void printASimpleClassRemovingAField() { c.getMembers().remove(0); assertEquals("class /*a comment*/ A {\t\t"+ EOL + EOL + - " void foo(int p ) { return 'z' \t; }}", lpp.print(c)); + " void foo(int p ) { return 'z' \t; }}", LexicalPreservingPrinter.print(c)); } @Test @@ -303,7 +301,7 @@ public void printASimpleMethodAddingAParameterToAMethodWithZeroParameters() { MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); m.addParameter("float", "p1"); - assertEquals("void foo(float p1) {}", lpp.print(m)); + assertEquals("void foo(float p1) {}", LexicalPreservingPrinter.print(m)); } @Test @@ -313,7 +311,7 @@ public void printASimpleMethodAddingAParameterToAMethodWithOneParameter() { MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); m.addParameter("float", "p2"); - assertEquals("void foo(char p1, float p2) {}", lpp.print(m)); + assertEquals("void foo(char p1, float p2) {}", LexicalPreservingPrinter.print(m)); } @Test @@ -323,7 +321,7 @@ public void printASimpleMethodRemovingAParameterToAMethodWithOneParameter() { MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); m.getParameters().remove(0); - assertEquals("void foo() {}", lpp.print(m)); + assertEquals("void foo() {}", LexicalPreservingPrinter.print(m)); } @Test @@ -333,7 +331,7 @@ public void printASimpleMethodRemovingParameterOneFromMethodWithTwoParameters() MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); m.getParameters().remove(0); - assertEquals("void foo(int p2) {}", lpp.print(m)); + assertEquals("void foo(int p2) {}", LexicalPreservingPrinter.print(m)); } @Test @@ -343,7 +341,7 @@ public void printASimpleMethodRemovingParameterTwoFromMethodWithTwoParameters() MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); m.getParameters().remove(1); - assertEquals("void foo(char p1) {}", lpp.print(m)); + assertEquals("void foo(char p1) {}", LexicalPreservingPrinter.print(m)); } @Test @@ -359,7 +357,7 @@ public void printASimpleMethodAddingAStatement() { MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); assertEquals("void foo(char p1, int p2) {"+EOL + " 10 + 2;"+ EOL + - "}", lpp.print(m)); + "}", LexicalPreservingPrinter.print(m)); } @Test @@ -368,7 +366,7 @@ public void printASimpleImport() { considerCode(code); ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); - assertEquals("import a.b.c.D;", lpp.print(imp)); + assertEquals("import a.b.c.D;", LexicalPreservingPrinter.print(imp)); } @Test @@ -377,7 +375,7 @@ public void printAnotherImport() { considerCode(code); ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); - assertEquals("import com.github.javaparser.ast.CompilationUnit;", lpp.print(imp)); + assertEquals("import com.github.javaparser.ast.CompilationUnit;", LexicalPreservingPrinter.print(imp)); } @Test @@ -386,14 +384,14 @@ public void printAStaticImport() { considerCode(code); ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); - assertEquals("import static com.github.javaparser.ParseStart.*;", lpp.print(imp)); + assertEquals("import static com.github.javaparser.ParseStart.*;", LexicalPreservingPrinter.print(imp)); } @Test public void checkAnnidatedTypeParametersPrinting() { String code = "class A { private final Stack> its = new Stack>(); }"; considerCode(code); - assertEquals("class A { private final Stack> its = new Stack>(); }", lpp.print(cu)); + assertEquals("class A { private final Stack> its = new Stack>(); }", LexicalPreservingPrinter.print(cu)); } @Test @@ -401,7 +399,7 @@ public void printASingleCatch() { String code = "class A {{try { doit(); } catch (Exception e) {}}}"; considerCode(code); - assertEquals("class A {{try { doit(); } catch (Exception e) {}}}", lpp.print(cu)); + assertEquals("class A {{try { doit(); } catch (Exception e) {}}}", LexicalPreservingPrinter.print(cu)); } @Test @@ -409,7 +407,7 @@ public void printAMultiCatch() { String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; considerCode(code); - assertEquals("class A {{try { doit(); } catch (Exception | AssertionError e) {}}}", lpp.print(cu)); + assertEquals("class A {{try { doit(); } catch (Exception | AssertionError e) {}}}", LexicalPreservingPrinter.print(cu)); } @Test @@ -421,7 +419,7 @@ public void printASingleCatchType() { CatchClause catchClause = tryStmt.getCatchClauses().get(0); Type catchType = catchClause.getParameter().getType(); - assertEquals("Exception", lpp.print(catchType)); + assertEquals("Exception", LexicalPreservingPrinter.print(catchType)); } @Test @@ -433,7 +431,7 @@ public void printUnionType() { CatchClause catchClause = tryStmt.getCatchClauses().get(0); UnionType unionType = (UnionType)catchClause.getParameter().getType(); - assertEquals("Exception | AssertionError", lpp.print(unionType)); + assertEquals("Exception | AssertionError", LexicalPreservingPrinter.print(unionType)); } @Test @@ -445,7 +443,7 @@ public void printParameterHavingUnionType() { CatchClause catchClause = tryStmt.getCatchClauses().get(0); Parameter parameter = catchClause.getParameter(); - assertEquals("Exception | AssertionError e", lpp.print(parameter)); + assertEquals("Exception | AssertionError e", LexicalPreservingPrinter.print(parameter)); } @Test @@ -453,7 +451,7 @@ public void printLambaWithUntypedParams() { String code = "class A {Function f = a -> a;}"; considerCode(code); - assertEquals("class A {Function f = a -> a;}", lpp.print(cu)); + assertEquals("class A {Function f = a -> a;}", LexicalPreservingPrinter.print(cu)); } @Test @@ -462,7 +460,7 @@ public void printAModuleInfoSpecificKeywordUsedAsIdentifier1() { cu.getClassByName("module").get().setName("xyz"); - assertEquals("class xyz { }", lpp.print(cu)); + assertEquals("class xyz { }", LexicalPreservingPrinter.print(cu)); } @Test @@ -471,7 +469,7 @@ public void printAModuleInfoSpecificKeywordUsedAsIdentifier2() { cu.getClassByName("xyz").get().setName("module"); - assertEquals("class module { }", lpp.print(cu)); + assertEquals("class module { }", LexicalPreservingPrinter.print(cu)); } // Issue 823: setPackageDeclaration on CU starting with a comment @@ -496,7 +494,7 @@ public void printLambdaIntersectionTypeAssignment() { " }}"; considerCode(code); - assertEquals(code, lpp.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu)); } @Test @@ -507,7 +505,7 @@ public void printLambdaIntersectionTypeReturn() { + "}}"; considerCode(code); - assertEquals(code, lpp.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu)); } // See issue #855 @@ -521,10 +519,8 @@ public void handleOverrideAnnotation() { " protected void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() .forEach(type -> type.getMembers() @@ -543,13 +539,13 @@ public void handleOverrideAnnotation() { EOL + " @Override" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } @Test public void preserveSpaceAsIsForASimpleClassWithMoreFormatting() throws IOException { considerExample("ASimpleClassWithMoreFormatting"); - assertEquals(readExample("ASimpleClassWithMoreFormatting"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting"), LexicalPreservingPrinter.print(cu)); } @Test @@ -558,7 +554,7 @@ public void renameASimpleClassWithMoreFormatting() throws IOException { cu.getClassByName("ASimpleClass").get() .setName("MyRenamedClass"); - assertEquals(readExample("ASimpleClassWithMoreFormatting_step1"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step1"), LexicalPreservingPrinter.print(cu)); } @Test @@ -571,7 +567,7 @@ public void theLexicalPreservationStringForAnAddedMethodShouldBeIndented() throw .getClassByName("MyRenamedClass").get() .addMethod("setAField", Modifier.PUBLIC); assertEquals("public void setAField() {" + EOL + - " }", lpp.print(setter)); + " }", LexicalPreservingPrinter.print(setter)); } @Test @@ -583,7 +579,7 @@ public void addMethodToASimpleClassWithMoreFormatting() throws IOException { MethodDeclaration setter = cu .getClassByName("MyRenamedClass").get() .addMethod("setAField", Modifier.PUBLIC); - assertEquals(readExample("ASimpleClassWithMoreFormatting_step2"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step2"), LexicalPreservingPrinter.print(cu)); } @Test @@ -596,7 +592,7 @@ public void addingParameterToAnAddedMethodInASimpleClassWithMoreFormatting() thr .getClassByName("MyRenamedClass").get() .addMethod("setAField", Modifier.PUBLIC); setter.addParameter("boolean", "aField"); - assertEquals(readExample("ASimpleClassWithMoreFormatting_step3"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step3"), LexicalPreservingPrinter.print(cu)); } @Test @@ -605,8 +601,8 @@ public void findIndentationOfEmptyMethod() throws IOException { MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() .getMethodsByName("setAField").get(0); - assertEquals(4, lpp.findIndentation(setter).size()); - assertEquals(4, lpp.findIndentation(setter.getBody().get()).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); } @Test @@ -615,9 +611,9 @@ public void findIndentationOfMethodWithStatements() throws IOException { MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() .getMethodsByName("setAField").get(0); - assertEquals(4, lpp.findIndentation(setter).size()); - assertEquals(4, lpp.findIndentation(setter.getBody().get()).size()); - assertEquals(8, lpp.findIndentation(setter.getBody().get().getStatement(0)).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); + assertEquals(8, LexicalPreservingPrinter.findIndentation(setter.getBody().get().getStatement(0)).size()); } @Test @@ -636,7 +632,7 @@ public void addingStatementToAnAddedMethodInASimpleClassWithMoreFormatting() thr new NameExpr("aField"), AssignExpr.Operator.ASSIGN ))); - assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); } @Test @@ -651,7 +647,7 @@ public void addingStatementToAnAddedMethodInASimpleClassWithMoreFormattingFromSt new NameExpr("aField"), AssignExpr.Operator.ASSIGN ))); - assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), lpp.print(cu)); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); } @Test @@ -753,7 +749,7 @@ public void nodeTextForModifiedMethod() throws IOException { assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RBRACE)); assertEquals(index, nodeText.getElements().size()); - nodeText = lpp.getOrCreateNodeText(setter.getBody().get().getStatement(0)); + nodeText = LexicalPreservingPrinter.getOrCreateNodeText(setter.getBody().get().getStatement(0)); index = 0; assertTrue(nodeText.getElements().get(index++).isChildOfClass(AssignExpr.class)); assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SEMICOLON)); @@ -776,7 +772,7 @@ public void addASecondStatementToExistingMethod() throws IOException { assertEquals("public void someMethod() {" + EOL + " String test = \"\";" + EOL + " String test2 = \"\";" + EOL - + " }", lpp.print(methodDeclaration)); + + " }", LexicalPreservingPrinter.print(methodDeclaration)); } // See issue #866 @@ -789,17 +785,14 @@ public void moveOverrideAnnotations() { " protected @Override void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() .forEach(type -> { type.getMembers() .forEach(member -> { - if (member instanceof MethodDeclaration) { - MethodDeclaration methodDeclaration = (MethodDeclaration) member; + member.ifMethodDeclaration(methodDeclaration -> { if (methodDeclaration.getAnnotationByName("Override").isPresent()) { while (methodDeclaration.getAnnotations().isNonEmpty()) { @@ -809,7 +802,7 @@ public void moveOverrideAnnotations() { methodDeclaration.addMarkerAnnotation("Override"); } - } + }); }); }); assertEquals("public class TestPage extends Page {" + EOL + @@ -818,7 +811,7 @@ public void moveOverrideAnnotations() { EOL + " @Override" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } // See issue #866 @@ -831,10 +824,8 @@ public void moveOrAddOverrideAnnotations() { " protected @Override void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() .forEach(type -> { @@ -860,7 +851,7 @@ public void moveOrAddOverrideAnnotations() { EOL + " @Override" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } // See issue #865 @@ -874,10 +865,8 @@ public void handleAddingMarkerAnnotation() { " protected void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() .forEach(type -> { @@ -898,7 +887,7 @@ public void handleAddingMarkerAnnotation() { EOL + " @Override" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } // See issue #865 @@ -911,21 +900,14 @@ public void handleOverrideMarkerAnnotation() { " protected void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() - .forEach(type -> { - type.getMembers() - .forEach(member -> { - if (member instanceof MethodDeclaration) { - MethodDeclaration methodDeclaration = (MethodDeclaration) member; - methodDeclaration.addMarkerAnnotation("Override"); - } - }); - }); + .forEach(type -> type.getMembers() + .forEach(member -> + member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addMarkerAnnotation("Override") + ))); assertEquals("public class TestPage extends Page {" + EOL + EOL + " @Override" + EOL + @@ -933,7 +915,7 @@ public void handleOverrideMarkerAnnotation() { EOL + " @Override" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } // See issue #865 @@ -946,21 +928,12 @@ public void handleOverrideAnnotationAlternative() { " protected void initializePage() {}" + EOL + "}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - - CompilationUnit cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.getTypes() - .forEach(type -> { - type.getMembers() - .forEach(member -> { - if (member instanceof MethodDeclaration) { - MethodDeclaration methodDeclaration = (MethodDeclaration) member; - methodDeclaration.addAnnotation("Override"); - } - }); - }); + .forEach(type -> type.getMembers() + .forEach(member -> member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addAnnotation("Override")))); assertEquals("public class TestPage extends Page {" + EOL + EOL + " @Override()" + EOL + @@ -968,7 +941,7 @@ public void handleOverrideAnnotationAlternative() { EOL + " @Override()" + EOL + " protected void initializePage() {}" + EOL + - "}", result.b.print(cu)); + "}", LexicalPreservingPrinter.print(cu)); } @Test @@ -977,9 +950,8 @@ public void invokeModifierVisitor() { + " Object f() {" + EOL + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + "}}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); - cu = result.a.getResult().get(); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); cu.accept(new ModifierVisitor<>(), null); } @@ -987,16 +959,13 @@ public void invokeModifierVisitor() { public void handleDeprecatedAnnotationFinalClass() { String code = "public final class A {}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); - CompilationUnit cu = result.a.getResult().get(); - cu.getTypes().forEach(type -> { - type.addAndGetAnnotation(Deprecated.class); - }); + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); assertEquals("@Deprecated()" + EOL + - "public final class A {}" , result.b.print(cu)); + "public final class A {}" , LexicalPreservingPrinter.print(cu)); } @@ -1004,17 +973,13 @@ public void handleDeprecatedAnnotationFinalClass() { public void handleDeprecatedAnnotationAbstractClass() { String code = "public abstract class A {}"; - Pair, LexicalPreservingPrinter> result = LexicalPreservingPrinter - .setup(ParseStart.COMPILATION_UNIT, Providers.provider(code)); + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); - CompilationUnit cu = result.a.getResult().get(); - cu.getTypes().forEach(type -> { - type.addAndGetAnnotation(Deprecated.class); - }); + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); assertEquals("@Deprecated()" + EOL + - "public abstract class A {}" , result.b.print(cu)); - + "public abstract class A {}" , LexicalPreservingPrinter.print(cu)); } }