From c5c7fa680be2233d0d28ce272a3614b5c2610bd9 Mon Sep 17 00:00:00 2001 From: RBRi Date: Mon, 15 Jan 2024 01:18:48 +0100 Subject: [PATCH] limit the length of the string to be used for indentation (#1428) * 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 https://github.com/mozilla/rhino/issues/1427 --- src/org/mozilla/javascript/ast/AstNode.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/org/mozilla/javascript/ast/AstNode.java b/src/org/mozilla/javascript/ast/AstNode.java index d17ad8e63b..fa9cdfc04f 100644 --- a/src/org/mozilla/javascript/ast/AstNode.java +++ b/src/org/mozilla/javascript/ast/AstNode.java @@ -71,6 +71,9 @@ public abstract class AstNode extends Node implements Comparable { protected AstNode inlineComment; private static Map 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"); @@ -120,6 +123,13 @@ public abstract class AstNode extends Node implements Comparable { 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, Serializable { @@ -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". */