Skip to content

Commit

Permalink
limit the length of the string to be used for indentation (#1428)
Browse files Browse the repository at this point in the history
* limit the length of the string to be used for indentation
* use a cache of precalculated strings instead of generating new ones over and over again

This addresses #1427
  • Loading branch information
rbri authored Jan 15, 2024
1 parent c4c7bf3 commit c5c7fa6
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/org/mozilla/javascript/ast/AstNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ public abstract class AstNode extends Node implements Comparable<AstNode> {
protected AstNode inlineComment;
private static Map<Integer, String> operatorNames = new HashMap<>();

private static final int MAX_INDENT = 42;
private static final String[] INDENTATIONS = new String[MAX_INDENT + 1];

static {
operatorNames.put(Token.IN, "in");
operatorNames.put(Token.TYPEOF, "typeof");
Expand Down Expand Up @@ -120,6 +123,13 @@ public abstract class AstNode extends Node implements Comparable<AstNode> {
operatorNames.put(Token.ASSIGN_BITXOR, "^=");
operatorNames.put(Token.ASSIGN_EXP, "**=");
operatorNames.put(Token.VOID, "void");

StringBuilder sb = new StringBuilder();
INDENTATIONS[0] = sb.toString();
for (int i = 1; i <= MAX_INDENT; i++) {
sb.append(" ");
INDENTATIONS[i] = sb.toString();
}
}

public static class PositionComparator implements Comparator<AstNode>, Serializable {
Expand Down Expand Up @@ -299,11 +309,8 @@ public String toSource() {
* @param indent the number of indentation steps
*/
public String makeIndent(int indent) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
return sb.toString();
indent = Math.min(MAX_INDENT, Math.max(0, indent));
return INDENTATIONS[indent];
}

/** Returns a short, descriptive name for the node, such as "ArrayComprehension". */
Expand Down

0 comments on commit c5c7fa6

Please sign in to comment.