Skip to content

Commit

Permalink
Some formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
matozoid committed Jan 28, 2018
1 parent 167673f commit 48789ab
Showing 1 changed file with 37 additions and 34 deletions.
Expand Up @@ -54,6 +54,7 @@
import static com.github.javaparser.TokenTypes.eolTokenKind; import static com.github.javaparser.TokenTypes.eolTokenKind;
import static com.github.javaparser.utils.Utils.assertNotNull; import static com.github.javaparser.utils.Utils.assertNotNull;
import static com.github.javaparser.utils.Utils.decapitalize; 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 * A Lexical Preserving Printer is used to capture all the lexical information while parsing, update them when
Expand All @@ -65,14 +66,16 @@ 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. * 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 // Factory methods
// //


/** /**
* Parse the code and setup the LexicalPreservingPrinter. * Parse the code and setup the LexicalPreservingPrinter.
*
* @deprecated use setup(Node) and the static methods on this class. * @deprecated use setup(Node) and the static methods on this class.
*/ */
public static <N extends Node> Pair<ParseResult<N>, LexicalPreservingPrinter> setup(ParseStart<N> parseStart, public static <N extends Node> Pair<ParseResult<N>, LexicalPreservingPrinter> setup(ParseStart<N> parseStart,
Expand All @@ -90,11 +93,12 @@ public static <N extends Node> Pair<ParseResult<N>, LexicalPreservingPrinter> se
* Prepares the node so it can be used in the print methods. * Prepares the node so it can be used in the print methods.
* The correct order is: * The correct order is:
* <ol> * <ol>
* <li>Parse some code</li> * <li>Parse some code</li>
* <li>Call this setup method on the result</li> * <li>Call this setup method on the result</li>
* <li>Make changes to the AST as desired</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>Use one of the print methods on this class to print out the original source code with your changes added</li>
* </ol> * </ol>
*
* @return the node passed as a parameter for your convenience. * @return the node passed as a parameter for your convenience.
*/ */
public static <N extends Node> N setup(N node) { public static <N extends Node> N setup(N node) {
Expand Down Expand Up @@ -143,13 +147,13 @@ public void concretePropertyChange(Node observedNode, ObservableProperty propert
if (oldValue == null) { if (oldValue == null) {
// Find the position of the comment node and put in front of it the comment and a newline // Find the position of the comment node and put in front of it the comment and a newline
int index = nodeText.findChild(observedNode); int index = nodeText.findChild(observedNode);
nodeText.addChild(index, (Comment)newValue); nodeText.addChild(index, (Comment) newValue);
nodeText.addToken(index + 1, eolTokenKind(), Utils.EOL); nodeText.addToken(index + 1, eolTokenKind(), Utils.EOL);
} else if (newValue == null) { } else if (newValue == null) {
if (oldValue instanceof JavadocComment) { if (oldValue instanceof JavadocComment) {
JavadocComment javadocComment = (JavadocComment)oldValue; JavadocComment javadocComment = (JavadocComment) oldValue;
List<TokenTextElement> matchingTokens = nodeText.getElements().stream().filter(e -> e.isToken(JAVADOC_COMMENT) 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) { if (matchingTokens.size() != 1) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
Expand All @@ -163,13 +167,13 @@ public void concretePropertyChange(Node observedNode, ObservableProperty propert
} }
} else { } else {
if (oldValue instanceof JavadocComment) { if (oldValue instanceof JavadocComment) {
JavadocComment oldJavadocComment = (JavadocComment)oldValue; JavadocComment oldJavadocComment = (JavadocComment) oldValue;
List<TokenTextElement> matchingTokens = nodeText.getElements().stream().filter(e -> e.isToken(JAVADOC_COMMENT) 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) { if (matchingTokens.size() != 1) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
JavadocComment newJavadocComment = (JavadocComment)newValue; JavadocComment newJavadocComment = (JavadocComment) newValue;
nodeText.replace(matchingTokens.get(0), new TokenTextElement(JAVADOC_COMMENT, "/**" + newJavadocComment.getContent() + "*/")); nodeText.replace(matchingTokens.get(0), new TokenTextElement(JAVADOC_COMMENT, "/**" + newJavadocComment.getContent() + "*/"));
} else { } else {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
Expand All @@ -191,7 +195,7 @@ public void concreteListChange(NodeList changedList, ListChangeType type, int in
if (type == ListChangeType.REMOVAL) { if (type == ListChangeType.REMOVAL) {
new LexicalDifferenceCalculator().calculateListRemovalDifference(findNodeListName(changedList), changedList, index).apply(nodeText, changedList.getParentNodeForChildren()); new LexicalDifferenceCalculator().calculateListRemovalDifference(findNodeListName(changedList), changedList, index).apply(nodeText, changedList.getParentNodeForChildren());
} else if (type == ListChangeType.ADDITION) { } 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 { } else {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
Expand Down Expand Up @@ -267,7 +271,7 @@ private static void storeInitialTextForOneNode(Node node, List<JavaToken> nodeTo
for (JavaToken token : nodeTokens) { for (JavaToken token : nodeTokens) {
elements.add(new Pair<>(token.getRange().get(), new TokenTextElement(token))); 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()))); node.setData(NODE_TEXT_DATA, new NodeText(elements.stream().map(p -> p.b).collect(Collectors.toList())));
} }


Expand Down Expand Up @@ -331,9 +335,9 @@ public static void print(Node node, Writer writer) throws IOException {
// Methods to handle transformations // Methods to handle transformations
// //


private static NodeText prettyPrintingTextNode(Node node, NodeText nodeText) { private static void prettyPrintingTextNode(Node node, NodeText nodeText) {
if (node instanceof PrimitiveType) { if (node instanceof PrimitiveType) {
PrimitiveType primitiveType = (PrimitiveType)node; PrimitiveType primitiveType = (PrimitiveType) node;
switch (primitiveType.getType()) { switch (primitiveType.getType()) {
case BOOLEAN: case BOOLEAN:
nodeText.addToken(BOOLEAN, node.toString()); nodeText.addToken(BOOLEAN, node.toString());
Expand Down Expand Up @@ -362,14 +366,14 @@ private static NodeText prettyPrintingTextNode(Node node, NodeText nodeText) {
default: default:
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
return nodeText; return;
} }
if (node instanceof JavadocComment) { if (node instanceof JavadocComment) {
nodeText.addToken(JAVADOC_COMMENT, "/**"+((JavadocComment)node).getContent()+"*/"); nodeText.addToken(JAVADOC_COMMENT, "/**" + ((JavadocComment) node).getContent() + "*/");
return nodeText; 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) { private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText) {
Expand All @@ -379,7 +383,7 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText)


boolean pendingIndentation = false; boolean pendingIndentation = false;
for (CsmElement element : calculatedSyntaxModel.elements) { 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); indentation.forEach(nodeText::addElement);
} }
pendingIndentation = false; pendingIndentation = false;
Expand All @@ -392,7 +396,7 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText)
pendingIndentation = true; pendingIndentation = true;
} }
} else if (element instanceof CsmMix) { } else if (element instanceof CsmMix) {
CsmMix csmMix = (CsmMix)element; CsmMix csmMix = (CsmMix) element;
csmMix.getElements().forEach(e -> interpret(node, e, nodeText)); csmMix.getElements().forEach(e -> interpret(node, e, nodeText));
} else { } else {
throw new UnsupportedOperationException(element.getClass().getSimpleName()); throw new UnsupportedOperationException(element.getClass().getSimpleName());
Expand All @@ -402,16 +406,15 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText)
// so they have to be handled in a special way // so they have to be handled in a special way
if (node instanceof VariableDeclarator) { if (node instanceof VariableDeclarator) {
VariableDeclarator variableDeclarator = (VariableDeclarator) node; VariableDeclarator variableDeclarator = (VariableDeclarator) node;
variableDeclarator.getParentNode().ifPresent(parent -> { variableDeclarator.getParentNode().ifPresent(parent ->
NodeWithVariables<?> nodeWithVariables = (NodeWithVariables) parent; ((NodeWithVariables<?>) parent).getMaximumCommonType().ifPresent(mct -> {
nodeWithVariables.getMaximumCommonType().ifPresent(mct -> { int extraArrayLevels = variableDeclarator.getType().getArrayLevel() - mct.getArrayLevel();
int extraArrayLevels = variableDeclarator.getType().getArrayLevel() - mct.getArrayLevel(); for (int i = 0; i < extraArrayLevels; i++) {
for (int i = 0; i < extraArrayLevels; i++) { nodeText.addElement(new TokenTextElement(LBRACKET));
nodeText.addElement(new TokenTextElement(LBRACKET)); nodeText.addElement(new TokenTextElement(RBRACKET));
nodeText.addElement(new TokenTextElement(RBRACKET)); }
} })
}); );
});
} }
return nodeText; return nodeText;
} }
Expand Down Expand Up @@ -440,7 +443,7 @@ static List<TokenTextElement> findIndentation(Node node) {
} }
} }
Collections.reverse(followingNewlines); Collections.reverse(followingNewlines);
for (int i=0;i<followingNewlines.size();i++){ for (int i = 0; i < followingNewlines.size(); i++) {
if (!followingNewlines.get(i).isSpaceOrTab()) { if (!followingNewlines.get(i).isSpaceOrTab()) {
return followingNewlines.subList(0, i); return followingNewlines.subList(0, i);
} }
Expand Down Expand Up @@ -473,7 +476,7 @@ private static ObservableProperty findNodeListName(NodeList nodeList) {
if (!(raw instanceof NodeList)) { if (!(raw instanceof NodeList)) {
throw new IllegalStateException("Expected NodeList, found " + raw.getClass().getCanonicalName()); throw new IllegalStateException("Expected NodeList, found " + raw.getClass().getCanonicalName());
} }
NodeList result = (NodeList)raw; NodeList result = (NodeList) raw;
if (result == nodeList) { if (result == nodeList) {
String name = m.getName(); String name = m.getName();
if (name.startsWith("get")) { if (name.startsWith("get")) {
Expand All @@ -486,7 +489,7 @@ private static ObservableProperty findNodeListName(NodeList nodeList) {
} }
} else if (m.getParameterCount() == 0 && isReturningOptionalNodeList(m)) { } else if (m.getParameterCount() == 0 && isReturningOptionalNodeList(m)) {
try { try {
Optional<NodeList> raw = (Optional<NodeList>)m.invoke(parent); Optional<NodeList<?>> raw = (Optional<NodeList<?>>) m.invoke(parent);
if (raw.isPresent() && raw.get() == nodeList) { if (raw.isPresent() && raw.get() == nodeList) {
String name = m.getName(); String name = m.getName();
if (name.startsWith("get")) { if (name.startsWith("get")) {
Expand Down

0 comments on commit 48789ab

Please sign in to comment.