Skip to content

Commit

Permalink
Merge pull request #42914 from Shadow-Devil/stack-to-deque
Browse files Browse the repository at this point in the history
[Refactoring] Replace "Stack" with "Deque".
  • Loading branch information
gimantha authored Sep 14, 2024
2 parents 496fe85 + 13f8f45 commit 98a63a3
Show file tree
Hide file tree
Showing 33 changed files with 200 additions and 223 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

package io.ballerina.shell.cli.jline.parser;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

/**
* State machine implementation for ballerina parser.
Expand Down Expand Up @@ -65,12 +66,12 @@ public class ParserStateMachine {
CLOSE_PAREN, OPEN_PAREN,
CLOSE_SQ_BR, OPEN_SQ_BR);

private final Stack<Character> stack;
private final Deque<Character> stack;
private ParserState state;

public ParserStateMachine() {
this.state = ParserState.NORMAL;
this.stack = new Stack<>();
this.stack = new ArrayDeque<>();
}

public void feed(char character) {
Expand Down Expand Up @@ -138,9 +139,9 @@ private void normalStateOrAfterOperator(char character) {
case CLOSE_CURLY:
case CLOSE_PAREN:
case CLOSE_SQ_BR:
if (!stack.empty() && OPEN_BRACKETS.get(character).equals(stack.peek())) {
if (!stack.isEmpty() && OPEN_BRACKETS.get(character).equals(stack.peek())) {
stack.pop();
if (!stack.empty() && stack.peek() == BACKTICK) {
if (!stack.isEmpty() && stack.peek() == BACKTICK) {
state = ParserState.IN_TEMPLATE;
}
break;
Expand Down Expand Up @@ -238,7 +239,7 @@ private void inTemplateState(char character) {
state = ParserState.IN_TEMPLATE_AFTER_DOLLAR;
break;
case BACKTICK:
if (!stack.empty() && stack.peek() == BACKTICK) {
if (!stack.isEmpty() && stack.peek() == BACKTICK) {
state = ParserState.NORMAL;
stack.pop();
break;
Expand Down Expand Up @@ -310,6 +311,6 @@ public boolean isIncomplete() {
return true;
}
// Otherwise, all brackets/backticks are closed is completion
return !stack.empty();
return !stack.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@

import io.ballerina.shell.exceptions.PreprocessorException;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Stack;

/**
* Preprocessor to split the input into several statements
Expand Down Expand Up @@ -51,7 +52,7 @@ public Collection<String> process(String input) throws PreprocessorException {
List<String> snippets = new ArrayList<>();
StringBuilder builder = new StringBuilder();

Stack<Character> brackets = new Stack<>();
Deque<Character> brackets = new ArrayDeque<>();

boolean isInBacktickLiteral = false;
boolean isInQuoteLiteral = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

package io.ballerina.runtime.internal.scheduling;

import java.util.Stack;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
Expand All @@ -38,7 +39,7 @@ public class ItemGroup {
* Keep the list of items that should run on same thread.
* Using a stack to get advantage of the locality.
*/
Stack<SchedulerItem> items = new Stack<>();
Deque<SchedulerItem> items = new ArrayDeque<>();

/**
* Indicates this item is already in runnable list/executing or not.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@
import io.ballerina.runtime.internal.values.FutureValue;

import java.io.PrintStream;
import java.util.Deque;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Function;

import static io.ballerina.runtime.api.values.BError.ERROR_PRINT_PREFIX;
Expand All @@ -43,7 +44,7 @@ public class RuntimeRegistry {

private final Scheduler scheduler;
private final Set<BObject> listenerSet = ConcurrentHashMap.newKeySet();
private final Stack<BFunctionPointer<?, ?>> stopHandlerStack = new Stack<>();
private final Deque<BFunctionPointer<?, ?>> stopHandlerStack = new ConcurrentLinkedDeque<>();

private static final PrintStream outStream = System.err;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ private void run() {
}
postProcess(item, result, panic);
group.lock();
if ((isItemsEmpty = group.items.empty())) {
if ((isItemsEmpty = group.items.isEmpty())) {
group.scheduled.set(false);
}
group.unlock();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@
import io.ballerina.runtime.internal.scheduling.Strand;

import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
* {@code TransactionLocalContext} stores the transaction related information.
Expand All @@ -41,8 +42,8 @@ public class TransactionLocalContext {
private Map<String, Integer> allowedTransactionRetryCounts;
private Map<String, Integer> currentTransactionRetryCounts;
private Map<String, BallerinaTransactionContext> transactionContextStore;
private Stack<String> transactionBlockIdStack;
private Stack<TransactionFailure> transactionFailure;
private Deque<String> transactionBlockIdStack;
private Deque<TransactionFailure> transactionFailure;
private static final TransactionResourceManager transactionResourceManager =
TransactionResourceManager.getInstance();
private boolean isResourceParticipant;
Expand All @@ -59,8 +60,8 @@ private TransactionLocalContext(String globalTransactionId, String url, String p
this.allowedTransactionRetryCounts = new HashMap<>();
this.currentTransactionRetryCounts = new HashMap<>();
this.transactionContextStore = new HashMap<>();
this.transactionBlockIdStack = new Stack<>();
this.transactionFailure = new Stack<>();
this.transactionBlockIdStack = new ArrayDeque<>();
this.transactionFailure = new ArrayDeque<>();
this.rollbackOnlyError = null;
this.isTransactional = true;
this.transactionId = ValueCreator.createArrayValue(globalTransactionId.getBytes());
Expand Down Expand Up @@ -104,7 +105,7 @@ public void addCurrentTransactionBlockId(String blockId) {
}

public boolean hasTransactionBlock() {
return !transactionBlockIdStack.empty();
return !transactionBlockIdStack.isEmpty();
}

public String getURL() {
Expand Down Expand Up @@ -211,7 +212,7 @@ public void markFailure() {
}

public TransactionFailure getAndClearFailure() {
if (transactionFailure.empty()) {
if (transactionFailure.isEmpty()) {
return null;
}
TransactionFailure failure = transactionFailure.pop();
Expand All @@ -220,7 +221,7 @@ public TransactionFailure getAndClearFailure() {
}

public TransactionFailure getFailure() {
if (transactionFailure.empty()) {
if (transactionFailure.isEmpty()) {
return null;
}
return transactionFailure.peek();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@
import org.wso2.ballerinalang.compiler.util.Name;
import org.wso2.ballerinalang.compiler.util.Names;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
* Stores the state such as the current node, enclosing package, function etc, during bir generation.
Expand Down Expand Up @@ -59,15 +60,15 @@ class BIRGenEnv {
BIRBasicBlock enclOnFailEndBB;
BIRBasicBlock enclInnerOnFailEndBB;

Stack<List<BIRBasicBlock>> trapBlocks = new Stack<>();
Deque<List<BIRBasicBlock>> trapBlocks = new ArrayDeque<>();

Map<BlockNode, List<BIRVariableDcl>> varDclsByBlock = new HashMap<>();

// This is to hold variables to unlock in each scope
// for example when we are to return from somewhere, we need to unlock all the
// values in this list, but if we are to do break or continue, we need to pop
// list and unlock variables in that
Stack<BIRLockDetailsHolder> unlockVars = new Stack<>();
Deque<BIRLockDetailsHolder> unlockVars = new ArrayDeque<>();

// This is the basic block that contains the return instruction for the current function.
// A function can have only one basic block that has a return instruction.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,10 +307,12 @@
import org.wso2.ballerinalang.util.Flags;
import org.wso2.ballerinalang.util.Lists;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
Expand All @@ -321,7 +323,6 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -397,7 +398,7 @@ public class Desugar extends BLangNodeVisitor {
private ClassClosureDesugar classClosureDesugar;
private LargeMethodSplitter largeMethodSplitter;

public Stack<BLangLockStmt> enclLocks = new Stack<>();
public Deque<BLangLockStmt> enclLocks = new ArrayDeque<>();
private BLangOnFailClause onFailClause;
private boolean shouldReturnErrors;
private int transactionBlockCount;
Expand All @@ -423,8 +424,8 @@ public class Desugar extends BLangNodeVisitor {
private Set<BLangWorkerSendReceiveExpr.Channel> channelsWithinIfStmt = new LinkedHashSet<>();

// Safe navigation related variables
private Stack<BLangMatchStatement> matchStmtStack = new Stack<>();
Stack<BLangExpression> accessExprStack = new Stack<>();
private Deque<BLangMatchStatement> matchStmtStack = new ArrayDeque<>();
Deque<BLangExpression> accessExprStack = new ArrayDeque<>();
private BLangMatchClause successClause;
private BLangAssignment safeNavigationAssignment;
static boolean isJvmTarget = false;
Expand Down Expand Up @@ -10075,13 +10076,13 @@ private BLangExpression rewriteSafeNavigationExpr(BLangAccessExpression accessEx
handleSafeNavigation(blockStmt, accessExpr, accessExpr.getBType(), tempResultVar);

// Create a statement-expression including the match statement
BLangMatchStatement matchStmt = this.matchStmtStack.firstElement();
BLangMatchStatement matchStmt = this.matchStmtStack.getLast();
blockStmt.stmts.add(matchStmt);
BLangStatementExpression stmtExpression = createStatementExpression(blockStmt, tempResultVarRef);
stmtExpression.setBType(originalExprType);
// Reset the variables
this.matchStmtStack = new Stack<>();
this.accessExprStack = new Stack<>();
this.matchStmtStack = new ArrayDeque<>();
this.accessExprStack = new ArrayDeque<>();
this.successClause = null;
this.safeNavigationAssignment = null;
return stmtExpression;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
import org.wso2.ballerinalang.compiler.util.CompilerContext;
import org.wso2.ballerinalang.compiler.util.Name;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Stack;

import static io.ballerina.runtime.api.constants.RuntimeConstants.UNDERSCORE;

Expand Down Expand Up @@ -101,17 +101,17 @@ public String getNextAnonymousTypeKey(PackageID packageID) {
return ANON_TYPE + UNDERSCORE + nextValue;
}

public String getNextAnonymousTypeKey(PackageID packageID, Stack<String> suffixes) {
public String getNextAnonymousTypeKey(PackageID packageID, Collection<String> suffixes) {
if (suffixes.isEmpty()) {
return getNextAnonymousTypeKey(packageID);
}
return createAnonTypeName(suffixes, packageID);
}

private String createAnonTypeName(Stack<String> suffixes, PackageID pkgId) {
private String createAnonTypeName(Collection<String> suffixes, PackageID pkgId) {
StringBuilder name = new StringBuilder(ANON_TYPE);
for (int i = suffixes.size() - 1; i >= 0; i--) {
name.append(suffixes.elementAt(i)).append(DOLLAR);
for (String suffix : suffixes) {
name.append(suffix).append(DOLLAR);
}
Map<String, Integer> anonTypesNames = anonTypesNamesPerPkg.computeIfAbsent(pkgId, key -> new HashMap<>());
String nameStr = name.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -500,15 +500,16 @@
import org.wso2.ballerinalang.compiler.util.QuoteType;
import org.wso2.ballerinalang.compiler.util.TypeTags;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;

import static org.ballerinalang.model.elements.Flag.INCLUDED;
Expand Down Expand Up @@ -539,8 +540,8 @@ public class BLangNodeBuilder extends NodeTransformer<BLangNode> {
private BLangMissingNodesHelper missingNodesHelper;

/* To keep track of additional statements produced from multi-BLangNode resultant transformations */
private Stack<BLangStatement> additionalStatements = new Stack<>();
private final Stack<String> anonTypeNameSuffixes = new Stack<>();
private Deque<BLangStatement> additionalStatements = new ArrayDeque<>();
private final Deque<String> anonTypeNameSuffixes = new ArrayDeque<>();
/* To keep track if we are inside a block statment for the use of type definition creation */
private boolean isInLocalContext = false;
/* To keep track if we are inside a finite context */
Expand All @@ -566,7 +567,7 @@ public List<org.ballerinalang.model.tree.Node> accept(Node node) {
BLangNode bLangNode = node.apply(this);
List<org.ballerinalang.model.tree.Node> nodes = new ArrayList<>();
// if not already consumed, add left-over statements
while (!additionalStatements.empty()) {
while (!additionalStatements.isEmpty()) {
nodes.add(additionalStatements.pop());
}
nodes.add(bLangNode);
Expand Down Expand Up @@ -1681,7 +1682,7 @@ public BLangNode transform(FunctionBodyBlockNode functionBodyBlockNode) {
for (NamedWorkerDeclarationNode workerDeclarationNode : namedWorkerDeclarator.namedWorkerDeclarations()) {
stmtList.add((BLangStatement) workerDeclarationNode.apply(this));
// Consume resultant additional statements
while (!this.additionalStatements.empty()) {
while (!this.additionalStatements.isEmpty()) {
stmtList.add(additionalStatements.pop());
}
}
Expand Down Expand Up @@ -5433,7 +5434,7 @@ private void generateForkStatements(List<BLangStatement> statements, ForkStateme
function.anonForkName = nextAnonymousForkKey;

statements.add(workerDef);
while (!this.additionalStatements.empty()) {
while (!this.additionalStatements.isEmpty()) {
statements.add(additionalStatements.pop());
}
forkJoin.addWorkers(workerDef);
Expand Down
Loading

0 comments on commit 98a63a3

Please sign in to comment.