use of com.github.javaparser.ast.type.PrimitiveType in project javaparser by javaparser.
the class Difference method apply.
/**
* Node that we have calculate the Difference we can apply to a concrete NodeText, modifying it according
* to the difference (adding and removing the elements provided).
*/
void apply(NodeText nodeText, Node node) {
if (nodeText == null) {
throw new NullPointerException();
}
boolean addedIndentation = false;
List<TokenTextElement> indentation = LexicalPreservingPrinter.findIndentation(node);
int diffIndex = 0;
int nodeTextIndex = 0;
do {
if (diffIndex < this.elements.size() && nodeTextIndex >= nodeText.getElements().size()) {
DifferenceElement diffEl = elements.get(diffIndex);
if (diffEl instanceof Kept) {
Kept kept = (Kept) diffEl;
if (kept.element instanceof CsmToken) {
CsmToken csmToken = (CsmToken) kept.element;
if (TokenTypes.isWhitespaceOrComment(csmToken.getTokenType())) {
diffIndex++;
} else {
throw new IllegalStateException("Cannot keep element because we reached the end of nodetext: " + nodeText + ". Difference: " + this);
}
} else {
throw new IllegalStateException("Cannot keep element because we reached the end of nodetext: " + nodeText + ". Difference: " + this);
}
} else if (diffEl instanceof Added) {
nodeText.addElement(nodeTextIndex, toTextElement(((Added) diffEl).element));
nodeTextIndex++;
diffIndex++;
} else {
throw new UnsupportedOperationException(diffEl.getClass().getSimpleName());
}
} else if (diffIndex >= this.elements.size() && nodeTextIndex < nodeText.getElements().size()) {
TextElement nodeTextEl = nodeText.getElements().get(nodeTextIndex);
if (nodeTextEl.isWhiteSpaceOrComment()) {
nodeTextIndex++;
} else {
throw new UnsupportedOperationException("NodeText: " + nodeText + ". Difference: " + this + " " + nodeTextEl);
}
} else {
DifferenceElement diffEl = elements.get(diffIndex);
TextElement nodeTextEl = nodeText.getElements().get(nodeTextIndex);
if (diffEl instanceof Added) {
CsmElement addedElement = ((Added) diffEl).element;
if (addedElement instanceof CsmIndent) {
for (int i = 0; i < STANDARD_INDENTATION_SIZE; i++) {
indentation.add(new TokenTextElement(GeneratedJavaParserConstants.SPACE));
}
addedIndentation = true;
diffIndex++;
continue;
}
if (addedElement instanceof CsmUnindent) {
for (int i = 0; i < STANDARD_INDENTATION_SIZE && !indentation.isEmpty(); i++) {
indentation.remove(indentation.size() - 1);
}
addedIndentation = false;
diffIndex++;
continue;
}
TextElement textElement = toTextElement(addedElement);
boolean used = false;
if (nodeTextIndex > 0 && nodeText.getElements().get(nodeTextIndex - 1).isNewline()) {
for (TextElement e : processIndentation(indentation, nodeText.getElements().subList(0, nodeTextIndex - 1))) {
nodeText.addElement(nodeTextIndex++, e);
}
} else if (isAfterLBrace(nodeText, nodeTextIndex) && !isAReplacement(diffIndex)) {
if (textElement.isNewline()) {
used = true;
}
nodeText.addElement(nodeTextIndex++, new TokenTextElement(TokenTypes.eolTokenKind()));
// This remove the space in "{ }" when adding a new line
while (nodeText.getElements().get(nodeTextIndex).isSpaceOrTab()) {
nodeText.getElements().remove(nodeTextIndex);
}
for (TextElement e : processIndentation(indentation, nodeText.getElements().subList(0, nodeTextIndex - 1))) {
nodeText.addElement(nodeTextIndex++, e);
}
// inserted by us in this transformation we do not want to insert it again
if (!addedIndentation) {
for (TextElement e : indentationBlock()) {
nodeText.addElement(nodeTextIndex++, e);
}
}
}
if (!used) {
nodeText.addElement(nodeTextIndex, textElement);
nodeTextIndex++;
}
if (textElement.isNewline()) {
boolean followedByUnindent = (diffIndex + 1) < elements.size() && elements.get(diffIndex + 1).isAdded() && elements.get(diffIndex + 1).getElement() instanceof CsmUnindent;
nodeTextIndex = adjustIndentation(indentation, nodeText, nodeTextIndex, followedByUnindent);
}
diffIndex++;
} else if (diffEl instanceof Kept) {
Kept kept = (Kept) diffEl;
if (nodeTextEl.isComment()) {
nodeTextIndex++;
} else if ((kept.element instanceof CsmChild) && nodeTextEl instanceof ChildTextElement) {
diffIndex++;
nodeTextIndex++;
} else if ((kept.element instanceof CsmChild) && nodeTextEl instanceof TokenTextElement) {
if (nodeTextEl.isWhiteSpaceOrComment()) {
nodeTextIndex++;
} else {
if (kept.element instanceof CsmChild) {
CsmChild keptChild = (CsmChild) kept.element;
if (keptChild.getChild() instanceof PrimitiveType) {
nodeTextIndex++;
diffIndex++;
} else {
throw new UnsupportedOperationException("kept " + kept.element + " vs " + nodeTextEl);
}
} else {
throw new UnsupportedOperationException("kept " + kept.element + " vs " + nodeTextEl);
}
}
} else if ((kept.element instanceof CsmToken) && nodeTextEl instanceof TokenTextElement) {
CsmToken csmToken = (CsmToken) kept.element;
TokenTextElement nodeTextToken = (TokenTextElement) nodeTextEl;
if (csmToken.getTokenType() == nodeTextToken.getTokenKind()) {
nodeTextIndex++;
diffIndex++;
} else if (TokenTypes.isWhitespaceOrComment(csmToken.getTokenType())) {
diffIndex++;
} else if (nodeTextToken.isWhiteSpaceOrComment()) {
nodeTextIndex++;
} else {
throw new UnsupportedOperationException("Csm token " + csmToken + " NodeText TOKEN " + nodeTextToken);
}
} else if ((kept.element instanceof CsmToken) && ((CsmToken) kept.element).isWhiteSpace()) {
diffIndex++;
} else if (kept.element instanceof CsmIndent) {
// Nothing to do
diffIndex++;
} else if (kept.element instanceof CsmUnindent) {
// Nothing to do, beside considering indentation
diffIndex++;
for (int i = 0; i < STANDARD_INDENTATION_SIZE && nodeTextIndex >= 1 && nodeText.getTextElement(nodeTextIndex - 1).isSpaceOrTab(); i++) {
nodeText.removeElement(--nodeTextIndex);
}
} else {
throw new UnsupportedOperationException("kept " + kept.element + " vs " + nodeTextEl);
}
} else if (diffEl instanceof Removed) {
Removed removed = (Removed) diffEl;
if ((removed.element instanceof CsmChild) && nodeTextEl instanceof ChildTextElement) {
ChildTextElement actualChild = (ChildTextElement) nodeTextEl;
if (actualChild.isComment()) {
CsmChild csmChild = (CsmChild) removed.element;
// We expected to remove a proper node but we found a comment in between.
// If the comment is associated to the node we want to remove we remove it as well, otherwise we keep it
Comment comment = (Comment) actualChild.getChild();
if (!comment.isOrphan() && comment.getCommentedNode().isPresent() && comment.getCommentedNode().get().equals(csmChild.getChild())) {
nodeText.removeElement(nodeTextIndex);
} else {
nodeTextIndex++;
}
} else {
nodeText.removeElement(nodeTextIndex);
if (nodeTextIndex < nodeText.getElements().size() && nodeText.getElements().get(nodeTextIndex).isNewline()) {
nodeTextIndex = considerCleaningTheLine(nodeText, nodeTextIndex);
} else {
if (diffIndex + 1 >= this.getElements().size() || !(this.getElements().get(diffIndex + 1) instanceof Added)) {
nodeTextIndex = considerEnforcingIndentation(nodeText, nodeTextIndex);
}
// If in front we have one space and before also we had space let's drop one space
if (nodeText.getElements().size() > nodeTextIndex && nodeTextIndex > 0) {
if (nodeText.getElements().get(nodeTextIndex).isWhiteSpace() && nodeText.getElements().get(nodeTextIndex - 1).isWhiteSpace()) {
// However we do not want to do that when we are about to adding or removing elements
if ((diffIndex + 1) == this.elements.size() || (elements.get(diffIndex + 1) instanceof Kept)) {
nodeText.getElements().remove(nodeTextIndex--);
}
}
}
}
diffIndex++;
}
} else if ((removed.element instanceof CsmToken) && nodeTextEl instanceof TokenTextElement && ((CsmToken) removed.element).getTokenType() == ((TokenTextElement) nodeTextEl).getTokenKind()) {
nodeText.removeElement(nodeTextIndex);
diffIndex++;
} else if (nodeTextEl instanceof TokenTextElement && nodeTextEl.isWhiteSpaceOrComment()) {
nodeTextIndex++;
} else if (removed.element instanceof CsmChild && ((CsmChild) removed.element).getChild() instanceof PrimitiveType) {
if (isPrimitiveType(nodeTextEl)) {
nodeText.removeElement(nodeTextIndex);
diffIndex++;
} else {
throw new UnsupportedOperationException("removed " + removed.element + " vs " + nodeTextEl);
}
} else if (removed.element instanceof CsmToken && ((CsmToken) removed.element).isWhiteSpace()) {
diffIndex++;
} else if (nodeTextEl.isWhiteSpace()) {
nodeTextIndex++;
} else {
throw new UnsupportedOperationException("removed " + removed.element + " vs " + nodeTextEl);
}
} else if (diffEl instanceof Reshuffled) {
// First, let's see how many tokens we need to attribute to the previous version of the of the CsmMix
Reshuffled reshuffled = (Reshuffled) diffEl;
CsmMix elementsFromPreviousOrder = reshuffled.previousOrder;
CsmMix elementsFromNextOrder = reshuffled.element;
// This contains indexes from elementsFromNextOrder to indexes from elementsFromPreviousOrder
Map<Integer, Integer> correspondanceBetweenNextOrderAndPreviousOrder = new HashMap<>();
for (int ni = 0; ni < elementsFromNextOrder.getElements().size(); ni++) {
boolean found = false;
CsmElement ne = elementsFromNextOrder.getElements().get(ni);
for (int pi = 0; pi < elementsFromPreviousOrder.getElements().size() && !found; pi++) {
CsmElement pe = elementsFromPreviousOrder.getElements().get(pi);
if (!correspondanceBetweenNextOrderAndPreviousOrder.values().contains(pi) && matching(ne, pe)) {
found = true;
correspondanceBetweenNextOrderAndPreviousOrder.put(ni, pi);
}
}
}
// We now find out which Node Text elements corresponds to the elements in the original CSM
final int startNodeTextIndex = nodeTextIndex;
final Set<Integer> usedIndexes = new HashSet<>();
List<Integer> nodeTextIndexOfPreviousElements = elementsFromPreviousOrder.getElements().stream().map(it -> findIndexOfCorrespondingNodeTextElement(it, nodeText, startNodeTextIndex, usedIndexes, node)).collect(Collectors.toList());
Map<Integer, Integer> nodeTextIndexToPreviousCSMIndex = new HashMap<>();
for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) {
int value = nodeTextIndexOfPreviousElements.get(i);
if (value != -1) {
nodeTextIndexToPreviousCSMIndex.put(value, i);
}
}
int lastNodeTextIndex = nodeTextIndexOfPreviousElements.stream().max(Integer::compareTo).orElse(-1);
// Elements to be added at the end
List<CsmElement> elementsToBeAddedAtTheEnd = new LinkedList<>();
Map<Integer, List<CsmElement>> elementsToAddBeforeGivenOriginalCSMElement = new HashMap<>();
for (int ni = 0; ni < elementsFromNextOrder.getElements().size(); ni++) {
// If it has a mapping, then it is kept
if (!correspondanceBetweenNextOrderAndPreviousOrder.containsKey(ni)) {
// Ok, it is something new. Where to put it? Let's see what is the first following
// element that has a mapping
int originalCsmIndex = -1;
for (int nj = ni + 1; nj < elementsFromNextOrder.getElements().size() && originalCsmIndex == -1; nj++) {
if (correspondanceBetweenNextOrderAndPreviousOrder.containsKey(nj)) {
originalCsmIndex = correspondanceBetweenNextOrderAndPreviousOrder.get(nj);
if (!elementsToAddBeforeGivenOriginalCSMElement.containsKey(originalCsmIndex)) {
elementsToAddBeforeGivenOriginalCSMElement.put(originalCsmIndex, new LinkedList<>());
}
elementsToAddBeforeGivenOriginalCSMElement.get(originalCsmIndex).add(elementsFromNextOrder.getElements().get(ni));
}
}
// it does not preceed anything, so it goes at the end
if (originalCsmIndex == -1) {
elementsToBeAddedAtTheEnd.add(elementsFromNextOrder.getElements().get(ni));
}
}
}
// We go over the original node text elements, in the order they appear in the NodeText.
// Considering an original node text element (ONE)
// * we verify if it corresponds to a CSM element. If it does not we just move on, otherwise
// we find the correspond OCE (Original CSM Element)
// * we first add new elements that are marked to be added before OCE
// * if OCE is marked to be present also in the "after" CSM we add a kept element,
// otherwise we add a removed element
this.getElements().remove(diffIndex);
int diffElIterator = diffIndex;
if (lastNodeTextIndex != -1) {
for (int ntIndex = startNodeTextIndex; ntIndex <= lastNodeTextIndex; ntIndex++) {
if (nodeTextIndexToPreviousCSMIndex.containsKey(ntIndex)) {
int indexOfOriginalCSMElement = nodeTextIndexToPreviousCSMIndex.get(ntIndex);
if (elementsToAddBeforeGivenOriginalCSMElement.containsKey(indexOfOriginalCSMElement)) {
for (CsmElement elementToAdd : elementsToAddBeforeGivenOriginalCSMElement.get(indexOfOriginalCSMElement)) {
elements.add(diffElIterator++, new Added(elementToAdd));
}
}
CsmElement originalCSMElement = elementsFromPreviousOrder.getElements().get(indexOfOriginalCSMElement);
boolean toBeKept = correspondanceBetweenNextOrderAndPreviousOrder.containsValue(indexOfOriginalCSMElement);
if (toBeKept) {
elements.add(diffElIterator++, new Kept(originalCSMElement));
} else {
elements.add(diffElIterator++, new Removed(originalCSMElement));
}
}
// else we have a simple node text element, without associated csm element, just keep ignore it
}
}
// add all of them
for (CsmElement elementToAdd : elementsToBeAddedAtTheEnd) {
elements.add(diffElIterator++, new Added(elementToAdd));
}
} else {
throw new UnsupportedOperationException("" + diffEl + " vs " + nodeTextEl);
}
}
} while (diffIndex < this.elements.size() || nodeTextIndex < nodeText.getElements().size());
}
use of com.github.javaparser.ast.type.PrimitiveType in project javaparser by javaparser.
the class NodeTest method registerWithJustNodeMode.
@Test
public void registerWithJustNodeMode() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.JUST_THIS_NODE);
assertEquals(Arrays.asList(), changes);
cu.getClassByName("A").get().setName("MyCoolClass");
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0");
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
}
use of com.github.javaparser.ast.type.PrimitiveType in project javaparser by javaparser.
the class NodeTest method registerSubTree.
@Test
public void registerSubTree() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.registerForSubtree(observer);
assertEquals(Arrays.asList(), changes);
cu.getClassByName("A").get().setName("MyCoolClass");
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", "FieldDeclaration.maximum_common_type changed from int to boolean", "VariableDeclarator.type changed from int to boolean"), changes);
cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", "FieldDeclaration.maximum_common_type changed from int to boolean", "VariableDeclarator.type changed from int to boolean", "Parameter.name changed from p to myParam"), changes);
}
use of com.github.javaparser.ast.type.PrimitiveType in project drools by kiegroup.
the class MaterializedLambdaPredicate method createTestMethod.
private void createTestMethod(EnumDeclaration classDeclaration) {
MethodDeclaration methodDeclaration = classDeclaration.addMethod("test", Modifier.Keyword.PUBLIC);
methodDeclaration.setThrownExceptions(NodeList.nodeList(toClassOrInterfaceType(java.lang.Exception.class)));
methodDeclaration.addAnnotation(createSimpleAnnotation("Override"));
methodDeclaration.setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
setMethodParameter(methodDeclaration);
ExpressionStmt clone = (ExpressionStmt) lambdaExpr.getBody().clone();
methodDeclaration.setBody(new BlockStmt(NodeList.nodeList(new ReturnStmt(clone.getExpression()))));
}
use of com.github.javaparser.ast.type.PrimitiveType in project javaflow by havardh.
the class ClassVisitor method visit.
@Override
public void visit(MethodDeclaration method, ClassBuilder builder) {
super.visit(method, builder);
TypeFactory factory = new TypeFactory(packageName, imports);
if (isClass((ClassOrInterfaceDeclaration) method.getParentNode()) && isGetter(method.getName(), method.getType().toString())) {
builder.withGetter(new Method(method.getName(), factory.build(method.getType().toString(), method.getType() instanceof PrimitiveType)));
}
}
Aggregations