Skip to content

Commit

Permalink
fix: (Java) Optimize super() code writing.
Browse files Browse the repository at this point in the history
  • Loading branch information
teletha committed Mar 14, 2023
1 parent 4d27de1 commit 3e16baf
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
37 changes: 37 additions & 0 deletions src/main/java/reincarnation/coder/Coder.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -49,6 +50,9 @@ public abstract class Coder<O extends CodingOption> {
/** The lazy writers. */
private final Deque<Ⅲ<Integer, Integer, Runnable>> lazy = new ArrayDeque();

/** The snapshot state. */
private final LinkedList<Integer> snapshots = new LinkedList();

/** The coding options. */
protected O options = I.make((Class<O>) Model.collectParameters(getClass(), Coder.class)[0]);

Expand Down Expand Up @@ -205,6 +209,39 @@ protected final void writeLazy(Runnable writer) {
lazy.addLast(I.pair(builder.length(), indentSize, writer));
}

/**
* Create a new snapshot point to revert.
*
* @param writer
*/
protected final void snapshot(Runnable writer) {
// create new snapshot
snapshots.addFirst(-builder.length());

try {
writer.run();
} finally {
int snapshot = snapshots.pollFirst();

// revert to the latest snapshot
if (0 < snapshot) {
builder.delete(snapshot, builder.length());
}
}
}

/**
* Revert to the latest snapshot.
*/
protected final void revert() {
if (!snapshots.isEmpty()) {
int point = snapshots.peekFirst();
if (point < 0) {
snapshots.set(0, -point);
}
}
}

/**
* {@inheritDoc}
*/
Expand Down
8 changes: 6 additions & 2 deletions src/main/java/reincarnation/coder/java/JavaCoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,9 @@ private Join thrower(Class[] exceptions) {
*/
@Override
public void writeStatement(Code<?> code) {
line(code, ";", code.comment().map(" // "::concat));
snapshot(() -> {
line(code, ";", code.comment().map(" //"::concat));
});
}

/**
Expand Down Expand Up @@ -651,7 +653,9 @@ public void writeConstructorCall(Constructor constructor, List<? extends Code> p
*/
@Override
public void writeSuperConstructorCall(Constructor constructor, List<? extends Code> params) {
if (!params.isEmpty()) {
if (params.isEmpty()) {
revert();
} else {
write("super", buildParameter(constructor, params));
}
}
Expand Down

0 comments on commit 3e16baf

Please sign in to comment.