diff options
8 files changed, 121 insertions, 91 deletions
diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/VariableDeclarator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/VariableDeclarator.java index 45b495945..de728cdc3 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/VariableDeclarator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/VariableDeclarator.java @@ -118,7 +118,7 @@ public final class VariableDeclarator extends Node implements NodeWithType<Varia if (vd.getParentNode().isPresent() && vd.getParentNode().get() instanceof NodeWithVariables) { NodeWithVariables nodeWithVariables = (NodeWithVariables) vd.getParentNode().get(); // We calculate the value the property will assume after the change will be completed - Type currentMaxCommonType = nodeWithVariables.getMaximumCommonType(); + Optional<Type> currentMaxCommonType = nodeWithVariables.getMaximumCommonType(); List<Type> types = new LinkedList<>(); int index = nodeWithVariables.getVariables().indexOf(vd); for (int i = 0; i < nodeWithVariables.getVariables().size(); i++) { @@ -128,8 +128,8 @@ public final class VariableDeclarator extends Node implements NodeWithType<Varia types.add(nodeWithVariables.getVariable(i).getType()); } } - Type newMaxCommonType = NodeWithVariables.calculateMaximumCommonType(types); - ((Node) nodeWithVariables).notifyPropertyChange(ObservableProperty.MAXIMUM_COMMON_TYPE, currentMaxCommonType, newMaxCommonType); + Optional<Type> newMaxCommonType = NodeWithVariables.calculateMaximumCommonType(types); + ((Node) nodeWithVariables).notifyPropertyChange(ObservableProperty.MAXIMUM_COMMON_TYPE, currentMaxCommonType.orElse(null), newMaxCommonType.orElse(null)); } } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java b/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java index 5cce28f5b..5daf38a14 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java @@ -29,6 +29,7 @@ import com.github.javaparser.ast.type.Type; import com.github.javaparser.metamodel.DerivedProperty; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; /** @@ -109,28 +110,28 @@ public interface NodeWithVariables<N extends Node> { * <br/>For <code>int[] a[][],b[],c[][];</code> this is int[][]. */ @DerivedProperty - default Type getMaximumCommonType() { - return calculateMaximumCommonType(this.getVariables().stream().map(v -> v.getType()).collect(Collectors.toList())); + default Optional<Type> getMaximumCommonType() { + return calculateMaximumCommonType(getVariables().stream().map(v -> v.getType()).collect(Collectors.toList())); } - static Type calculateMaximumCommonType(List<Type> types) { + static Optional<Type> calculateMaximumCommonType(List<Type> types) { // we use a local class because we cannot use an helper static method in an interface class Helper { // Conceptually: given a type we start from the Element Type and get as many array levels as indicated // From the implementation point of view we start from the actual type and we remove how many array // levels as needed to get the target level of arrays // It returns null if the type has less array levels then the desired target - private Type toArrayLevel(Type type, int level) { + private Optional<Type> toArrayLevel(Type type, int level) { if (level > type.getArrayLevel()) { - return null; + return Optional.empty(); } for (int i = type.getArrayLevel(); i > level; i--) { if (!(type instanceof ArrayType)) { - throw new AssertionError("The variables do not have a common type."); + return Optional.empty(); } type = ((ArrayType) type).getComponentType(); } - return type; + return Optional.of(type); } } @@ -145,8 +146,8 @@ public interface NodeWithVariables<N extends Node> { // the pretty-printed string got for a node. We just check all them are the same and if they // are we just just is not null Object[] values = types.stream().map(v -> { - Type t = helper.toArrayLevel(v, currentLevel); - return t == null ? null : t.toString(); + Optional<Type> t = helper.toArrayLevel(v, currentLevel); + return t.map(Node::toString).orElse(null); }).distinct().toArray(); if (values.length == 1 && values[0] != null) { level++; diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java index 9b8d56b74..b771c8eea 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java @@ -482,7 +482,11 @@ public class PrettyPrintVisitor implements VoidVisitor<Void> { printMemberAnnotations(n.getAnnotations(), arg); printModifiers(n.getModifiers()); if (!n.getVariables().isEmpty()) { - n.getMaximumCommonType().accept(this, arg); + Optional<Type> maximumCommonType = n.getMaximumCommonType(); + maximumCommonType.ifPresent(t -> t.accept(this, arg)); + if(!maximumCommonType.isPresent()){ + printer.print("???"); + } } printer.print(" "); @@ -502,25 +506,25 @@ public class PrettyPrintVisitor implements VoidVisitor<Void> { printComment(n.getComment(), arg); n.getName().accept(this, arg); - Optional<NodeWithVariables> ancestor = n.getAncestorOfType(NodeWithVariables.class); - if (!ancestor.isPresent()) { - throw new RuntimeException("Unable to work with VariableDeclarator not owned by a NodeWithVariables"); - } - Type commonType = ancestor.get().getMaximumCommonType(); + n.getAncestorOfType(NodeWithVariables.class).ifPresent(ancestor -> { + Optional<Type> maximumCommonType = ancestor.getMaximumCommonType(); + maximumCommonType.ifPresent(commonType -> { - Type type = n.getType(); + Type type = n.getType(); - ArrayType arrayType = null; + ArrayType arrayType = null; - for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) { - if (arrayType == null) { - arrayType = (ArrayType) type; - } else { - arrayType = (ArrayType) arrayType.getComponentType(); - } - printAnnotations(arrayType.getAnnotations(), true, arg); - printer.print("[]"); - } + for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) { + if (arrayType == null) { + arrayType = (ArrayType) type; + } else { + arrayType = (ArrayType) arrayType.getComponentType(); + } + printAnnotations(arrayType.getAnnotations(), true, arg); + printer.print("[]"); + } + }); + }); if (n.getInitializer().isPresent()) { printer.print(" = "); @@ -913,7 +917,7 @@ public class PrettyPrintVisitor implements VoidVisitor<Void> { printModifiers(n.getModifiers()); if (!n.getVariables().isEmpty()) { - n.getMaximumCommonType().accept(this, arg); + n.getMaximumCommonType().ifPresent(t -> t.accept(this, arg)); } printer.print(" "); 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 c874345e1..ef647fbf0 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 @@ -54,10 +54,11 @@ import static com.github.javaparser.GeneratedJavaParserConstants.*; import static com.github.javaparser.TokenTypes.eolTokenKind; import static com.github.javaparser.utils.Utils.assertNotNull; import static com.github.javaparser.utils.Utils.decapitalize; +import static java.util.Comparator.*; /** * A Lexical Preserving Printer is used to capture all the lexical information while parsing, update them when - * operating on the AST and then used them to reproduce the source code + * operating on the AST and then used them to reproduce the source code * in its original formatting including the AST changes. */ public class LexicalPreservingPrinter { @@ -65,7 +66,8 @@ public class LexicalPreservingPrinter { /** * The nodetext for a node is stored in the node's data field. This is the key to set and retrieve it. */ - public static final DataKey<NodeText> NODE_TEXT_DATA = new DataKey<NodeText>() { }; + public static final DataKey<NodeText> NODE_TEXT_DATA = new DataKey<NodeText>() { + }; // // Factory methods @@ -73,6 +75,7 @@ public class LexicalPreservingPrinter { /** * Parse the code and setup the LexicalPreservingPrinter. + * * @deprecated use setup(Node) and the static methods on this class. */ public static <N extends Node> Pair<ParseResult<N>, LexicalPreservingPrinter> setup(ParseStart<N> parseStart, @@ -90,11 +93,12 @@ public class LexicalPreservingPrinter { * Prepares the node so it can be used in the print methods. * The correct order is: * <ol> - * <li>Parse some code</li> - * <li>Call this setup method on the result</li> - * <li>Make changes to the AST as desired</li> - * <li>Use one of the print methods on this class to print out the original source code with your changes added</li> + * <li>Parse some code</li> + * <li>Call this setup method on the result</li> + * <li>Make changes to the AST as desired</li> + * <li>Use one of the print methods on this class to print out the original source code with your changes added</li> * </ol> + * * @return the node passed as a parameter for your convenience. */ public static <N extends Node> N setup(N node) { @@ -110,7 +114,7 @@ public class LexicalPreservingPrinter { }); return node; } - + // // Constructor and setup // @@ -143,13 +147,13 @@ public class LexicalPreservingPrinter { if (oldValue == null) { // Find the position of the comment node and put in front of it the comment and a newline int index = nodeText.findChild(observedNode); - nodeText.addChild(index, (Comment)newValue); + nodeText.addChild(index, (Comment) newValue); nodeText.addToken(index + 1, eolTokenKind(), Utils.EOL); } else if (newValue == null) { if (oldValue instanceof JavadocComment) { - JavadocComment javadocComment = (JavadocComment)oldValue; + JavadocComment javadocComment = (JavadocComment) oldValue; List<TokenTextElement> matchingTokens = nodeText.getElements().stream().filter(e -> e.isToken(JAVADOC_COMMENT) - && ((TokenTextElement)e).getText().equals("/**"+javadocComment.getContent()+"*/")).map(e -> (TokenTextElement)e).collect(Collectors.toList()); + && ((TokenTextElement) e).getText().equals("/**" + javadocComment.getContent() + "*/")).map(e -> (TokenTextElement) e).collect(Collectors.toList()); if (matchingTokens.size() != 1) { throw new IllegalStateException(); } @@ -163,13 +167,13 @@ public class LexicalPreservingPrinter { } } else { if (oldValue instanceof JavadocComment) { - JavadocComment oldJavadocComment = (JavadocComment)oldValue; + JavadocComment oldJavadocComment = (JavadocComment) oldValue; List<TokenTextElement> matchingTokens = nodeText.getElements().stream().filter(e -> e.isToken(JAVADOC_COMMENT) - && ((TokenTextElement)e).getText().equals("/**"+oldJavadocComment.getContent()+"*/")).map(e -> (TokenTextElement)e).collect(Collectors.toList()); + && ((TokenTextElement) e).getText().equals("/**" + oldJavadocComment.getContent() + "*/")).map(e -> (TokenTextElement) e).collect(Collectors.toList()); if (matchingTokens.size() != 1) { throw new IllegalStateException(); } - JavadocComment newJavadocComment = (JavadocComment)newValue; + JavadocComment newJavadocComment = (JavadocComment) newValue; nodeText.replace(matchingTokens.get(0), new TokenTextElement(JAVADOC_COMMENT, "/**" + newJavadocComment.getContent() + "*/")); } else { throw new UnsupportedOperationException(); @@ -191,7 +195,7 @@ public class LexicalPreservingPrinter { if (type == ListChangeType.REMOVAL) { new LexicalDifferenceCalculator().calculateListRemovalDifference(findNodeListName(changedList), changedList, index).apply(nodeText, changedList.getParentNodeForChildren()); } else if (type == ListChangeType.ADDITION) { - new LexicalDifferenceCalculator().calculateListAdditionDifference(findNodeListName(changedList),changedList, index, nodeAddedOrRemoved).apply(nodeText, changedList.getParentNodeForChildren()); + new LexicalDifferenceCalculator().calculateListAdditionDifference(findNodeListName(changedList), changedList, index, nodeAddedOrRemoved).apply(nodeText, changedList.getParentNodeForChildren()); } else { throw new UnsupportedOperationException(); } @@ -267,7 +271,7 @@ public class LexicalPreservingPrinter { for (JavaToken token : nodeTokens) { elements.add(new Pair<>(token.getRange().get(), new TokenTextElement(token))); } - elements.sort(Comparator.comparing(e -> e.a.begin)); + elements.sort(comparing(e -> e.a.begin)); node.setData(NODE_TEXT_DATA, new NodeText(elements.stream().map(p -> p.b).collect(Collectors.toList()))); } @@ -331,9 +335,9 @@ public class LexicalPreservingPrinter { // Methods to handle transformations // - private static NodeText prettyPrintingTextNode(Node node, NodeText nodeText) { + private static void prettyPrintingTextNode(Node node, NodeText nodeText) { if (node instanceof PrimitiveType) { - PrimitiveType primitiveType = (PrimitiveType)node; + PrimitiveType primitiveType = (PrimitiveType) node; switch (primitiveType.getType()) { case BOOLEAN: nodeText.addToken(BOOLEAN, node.toString()); @@ -362,14 +366,14 @@ public class LexicalPreservingPrinter { default: throw new IllegalArgumentException(); } - return nodeText; + return; } if (node instanceof JavadocComment) { - nodeText.addToken(JAVADOC_COMMENT, "/**"+((JavadocComment)node).getContent()+"*/"); - return nodeText; + nodeText.addToken(JAVADOC_COMMENT, "/**" + ((JavadocComment) node).getContent() + "*/"); + return; } - return interpret(node, ConcreteSyntaxModel.forClass(node.getClass()), nodeText); + interpret(node, ConcreteSyntaxModel.forClass(node.getClass()), nodeText); } private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText) { @@ -379,7 +383,7 @@ public class LexicalPreservingPrinter { boolean pendingIndentation = false; for (CsmElement element : calculatedSyntaxModel.elements) { - if (pendingIndentation && !(element instanceof CsmToken && ((CsmToken)element).isNewLine())) { + if (pendingIndentation && !(element instanceof CsmToken && ((CsmToken) element).isNewLine())) { indentation.forEach(nodeText::addElement); } pendingIndentation = false; @@ -392,7 +396,7 @@ public class LexicalPreservingPrinter { pendingIndentation = true; } } else if (element instanceof CsmMix) { - CsmMix csmMix = (CsmMix)element; + CsmMix csmMix = (CsmMix) element; csmMix.getElements().forEach(e -> interpret(node, e, nodeText)); } else { throw new UnsupportedOperationException(element.getClass().getSimpleName()); @@ -401,16 +405,16 @@ public class LexicalPreservingPrinter { // Array brackets are a pain... we do not have a way to represent them explicitly in the AST // so they have to be handled in a special way if (node instanceof VariableDeclarator) { - VariableDeclarator variableDeclarator = (VariableDeclarator)node; - if (!variableDeclarator.getParentNode().isPresent()) { - throw new RuntimeException("VariableDeclarator without parent: I cannot handle the array levels"); - } - NodeWithVariables<?> nodeWithVariables = (NodeWithVariables)variableDeclarator.getParentNode().get(); - int extraArrayLevels = variableDeclarator.getType().getArrayLevel() - nodeWithVariables.getMaximumCommonType().getArrayLevel(); - for (int i=0; i<extraArrayLevels; i++) { - nodeText.addElement(new TokenTextElement(LBRACKET)); - nodeText.addElement(new TokenTextElement(RBRACKET)); - } + VariableDeclarator variableDeclarator = (VariableDeclarator) node; + variableDeclarator.getParentNode().ifPresent(parent -> + ((NodeWithVariables<?>) parent).getMaximumCommonType().ifPresent(mct -> { + int extraArrayLevels = variableDeclarator.getType().getArrayLevel() - mct.getArrayLevel(); + for (int i = 0; i < extraArrayLevels; i++) { + nodeText.addElement(new TokenTextElement(LBRACKET)); + nodeText.addElement(new TokenTextElement(RBRACKET)); + } + }) + ); } return nodeText; } @@ -439,7 +443,7 @@ public class LexicalPreservingPrinter { } } Collections.reverse(followingNewlines); - for (int i=0;i<followingNewlines.size();i++){ + for (int i = 0; i < followingNewlines.size(); i++) { if (!followingNewlines.get(i).isSpaceOrTab()) { return followingNewlines.subList(0, i); } @@ -472,7 +476,7 @@ public class LexicalPreservingPrinter { if (!(raw instanceof NodeList)) { throw new IllegalStateException("Expected NodeList, found " + raw.getClass().getCanonicalName()); } - NodeList result = (NodeList)raw; + NodeList result = (NodeList) raw; if (result == nodeList) { String name = m.getName(); if (name.startsWith("get")) { @@ -485,7 +489,7 @@ public class LexicalPreservingPrinter { } } else if (m.getParameterCount() == 0 && isReturningOptionalNodeList(m)) { try { - Optional<NodeList> raw = (Optional<NodeList>)m.invoke(parent); + Optional<NodeList<?>> raw = (Optional<NodeList<?>>) m.invoke(parent); if (raw.isPresent() && raw.get() == nodeList) { String name = m.getName(); if (name.startsWith("get")) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java index 860fe6bc4..65ccedf00 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java @@ -53,7 +53,7 @@ public class FieldAccessContext extends AbstractJavaParserContext<FieldAccessExp @Override public SymbolReference<? extends ResolvedValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) { - if (wrappedNode.getField().toString().equals(name)) { + if (wrappedNode.getName().toString().equals(name)) { if (wrappedNode.getScope() instanceof ThisExpr) { ResolvedType typeOfThis = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode); return new SymbolSolver(typeSolver).solveSymbolInType(typeOfThis.asReferenceType().getTypeDeclaration(), name); @@ -75,18 +75,14 @@ public class FieldAccessContext extends AbstractJavaParserContext<FieldAccessExp @Override public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) { Expression scope = wrappedNode.getScope(); - if (wrappedNode.getField().toString().equals(name)) { + if (wrappedNode.getName().toString().equals(name)) { ResolvedType typeOfScope = JavaParserFacade.get(typeSolver).getType(scope); if (typeOfScope.isArray() && name.equals(ARRAY_LENGTH_FIELD_NAME)) { return Optional.of(new Value(ResolvedPrimitiveType.INT, ARRAY_LENGTH_FIELD_NAME)); } if (typeOfScope.isReferenceType()) { Optional<ResolvedType> typeUsage = typeOfScope.asReferenceType().getFieldType(name); - if (typeUsage.isPresent()) { - return Optional.of(new Value(typeUsage.get(), name)); - } else { - return Optional.empty(); - } + return typeUsage.map(resolvedType -> new Value(resolvedType, name)); } else { return Optional.empty(); } diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java index b8c95a6ac..dd8738ab0 100644 --- a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java @@ -42,22 +42,22 @@ public class PrettyPrintVisitorTest { @Test public void getMaximumCommonTypeWithoutAnnotations() { VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a[], b[]"); - assertEquals("int[]", vde1.getMaximumCommonType().toString()); + assertEquals("int[]", vde1.getMaximumCommonType().get().toString()); VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[][] a[], b[]"); - assertEquals("int[][][]", vde2.getMaximumCommonType().toString()); + assertEquals("int[][][]", vde2.getMaximumCommonType().get().toString()); VariableDeclarationExpr vde3 = JavaParser.parseVariableDeclarationExpr("int[][] a, b[]"); - assertEquals("int[][]", vde3.getMaximumCommonType().toString()); + assertEquals("int[][]", vde3.getMaximumCommonType().get().toString()); } @Test public void getMaximumCommonTypeWithAnnotations() { VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a @Foo [], b[]"); - assertEquals("int", vde1.getMaximumCommonType().toString()); + assertEquals("int", vde1.getMaximumCommonType().get().toString()); VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[]@Foo [] a[], b[]"); - assertEquals("int[] @Foo [][]", vde2.getMaximumCommonType().toString()); + assertEquals("int[] @Foo [][]", vde2.getMaximumCommonType().get().toString()); } private String print(Node node) { diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java index 88bd55924..fef360925 100644 --- a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java @@ -21,25 +21,26 @@ package com.github.javaparser.printer; -import com.github.javaparser.JavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.PrimitiveType; import org.junit.Test; +import static com.github.javaparser.JavaParser.*; import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; import static org.junit.Assert.assertEquals; public class PrettyPrinterTest { private String prettyPrintField(String code) { - CompilationUnit cu = JavaParser.parse(code); + CompilationUnit cu = parse(code); return new PrettyPrinter().print(cu.findFirst(FieldDeclaration.class).get()); } private String prettyPrintVar(String code) { - CompilationUnit cu = JavaParser.parse(code); + CompilationUnit cu = parse(code); return new PrettyPrinter().print(cu.findAll(VariableDeclarationExpr.class).get(0)); } @@ -82,7 +83,7 @@ public class PrettyPrinterTest { } private String prettyPrintConfigurable(String code) { - CompilationUnit cu = JavaParser.parse(code); + CompilationUnit cu = parse(code); PrettyPrinter printer = new PrettyPrinter(new PrettyPrinterConfiguration().setVisitorFactory(TestVisitor::new)); return printer.print(cu.findFirst(ClassOrInterfaceDeclaration.class).get()); } @@ -115,7 +116,7 @@ public class PrettyPrinterTest { "}" + EOL + ""; - assertEquals(expected, new PrettyPrinter(config).print(JavaParser.parse(code))); + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); } @Test @@ -132,7 +133,7 @@ public class PrettyPrinterTest { "}" + EOL + ""; - assertEquals(expected, new PrettyPrinter(config).print(JavaParser.parse(code))); + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); } @Test @@ -156,7 +157,7 @@ public class PrettyPrinterTest { "}" + EOL + ""; - assertEquals(expected, new PrettyPrinter(config).print(JavaParser.parse(code))); + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); } @Test @@ -173,18 +174,33 @@ public class PrettyPrinterTest { "}" + EOL + ""; - assertEquals(expected, new PrettyPrinter(config).print(JavaParser.parse(code))); + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); } @Test public void enumConstantsHorizontally() { - CompilationUnit cu = JavaParser.parse("enum X{A, B, C, D, E}"); + CompilationUnit cu = parse("enum X{A, B, C, D, E}"); assertEqualsNoEol("enum X {\n\n A, B, C, D, E\n}\n", new PrettyPrinter().print(cu)); } @Test public void enumConstantsVertically() { - CompilationUnit cu = JavaParser.parse("enum X{A, B, C, D, E, F}"); + CompilationUnit cu = parse("enum X{A, B, C, D, E, F}"); assertEqualsNoEol("enum X {\n\n A,\n B,\n C,\n D,\n E,\n F\n}\n", new PrettyPrinter().print(cu)); } + + @Test + public void printingInconsistentVariables() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int a, b;").asFieldDeclaration(); + + assertEquals("int a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(0).setType(PrimitiveType.doubleType()); + + assertEquals("??? a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(1).setType(PrimitiveType.doubleType()); + + assertEquals("double a, b;", fieldDeclaration.toString()); + } } diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java index eda719080..994f5d8b6 100644 --- a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java @@ -44,24 +44,33 @@ public class FieldDeclarationTransformationsTest extends AbstractLexicalPreservi // Modifiers @Test - public void addingModifiers() throws IOException { + public void addingModifiers() { FieldDeclaration it = consider("int A;"); it.setModifiers(EnumSet.of(Modifier.PUBLIC)); assertTransformedToString("public int A;", it); } @Test - public void removingModifiers() throws IOException { + public void removingModifiers() { FieldDeclaration it = consider("public int A;"); it.setModifiers(EnumSet.noneOf(Modifier.class)); assertTransformedToString("int A;", it); } @Test - public void replacingModifiers() throws IOException { + public void replacingModifiers() { FieldDeclaration it = consider("int A;"); it.setModifiers(EnumSet.of(Modifier.PROTECTED)); assertTransformedToString("protected int A;", it); } + @Test + public void changingTypes() { + FieldDeclaration it = consider("int a, b;"); + assertTransformedToString("int a, b;", it); + it.getVariable(0).setType("Xyz"); + assertTransformedToString(" a, b;", it); + it.getVariable(1).setType("Xyz"); + assertTransformedToString("Xyz a, b;", it); + } } |